Skip to content

clawd_code_sdk

Class info

Classes

Name Children Inherits
APIError
clawd_code_sdk._errors
Base exception for Anthropic API errors.
AuthenticationError
clawd_code_sdk._errors
Raised when API authentication fails (401).
    BillingError
    clawd_code_sdk._errors
    Raised when there's a billing issue with the API account.
      CLIConnectionError
      clawd_code_sdk._errors
      Raised when unable to connect to Claude Code.
      CLIJSONDecodeError
      clawd_code_sdk._errors
      Raised when unable to decode JSON from CLI output.
        CLINotFoundError
        clawd_code_sdk._errors
        Raised when Claude Code is not found or not installed.
          CanUseToolShadowedWarning
          clawd_code_sdk._errors
          ``on_permission`` is a callback, but some tool calls are auto-approved before it runs.
            ClaudeSDKError
            clawd_code_sdk._errors
            Base exception for all Claude SDK errors.
            ControlRequestError
            clawd_code_sdk._errors
            Raised when a control protocol request fails.
            ControlRequestTimeoutError
            clawd_code_sdk._errors
            Raised when a control protocol request times out.
              ForkSessionResult
              clawd_code_sdk._internal.session_mutations
              Result of a fork operation.
                InvalidRequestError
                clawd_code_sdk._errors
                Raised when the API request is invalid (400).
                  LineFramer
                  clawd_code_sdk._internal.transport.subprocess_utils
                  Reassembles complete lines from a stream that yields arbitrary chunks.
                    McpError
                    clawd_code_sdk._errors
                    Raised when an MCP-related control request fails.
                      ProcessError
                      clawd_code_sdk._errors
                      Raised when the CLI process fails.
                      RateLimitError
                      clawd_code_sdk._errors
                      Raised when API rate limits are exceeded (429).
                        ResultError
                        clawd_code_sdk._errors
                        The CLI reported an error result and then exited non-zero.
                          SdkMcpBridge
                          clawd_code_sdk._internal.sdk_mcp_bridge
                          Routes raw JSON-RPC for one in-process MCP server through mcp's memory transport.
                            SdkMcpBridgeError
                            clawd_code_sdk._internal.sdk_mcp_bridge
                            Raised when a message cannot be delivered to an SDK MCP server.
                              ServerError
                              clawd_code_sdk._errors
                              Raised when the API server encounters an error (500/529).
                                SubprocessCLITransport
                                clawd_code_sdk._internal.transport.subprocess_cli
                                Subprocess transport using Claude Code CLI.
                                  Transport
                                  clawd_code_sdk._internal.transport
                                  Abstract transport for Claude communication.

                                  Re-exported classes

                                  Class Module Description
                                  AgentDefinition clawd_code_sdk.models.agents User-facing agent definition configuration.
                                  AgentHookHandler clawd_code_sdk.models.hooks Agent hook handler with multi-turn tool access.
                                  AppliedSettings clawd_code_sdk.models.control The currently applied model and effort settings.
                                  AssistantMessage clawd_code_sdk.models.messages Assistant message with content blocks.
                                  BaseHookInput clawd_code_sdk.models.hooks Base hook input fields present across many hook events.
                                  BaseResultMessage clawd_code_sdk.models.messages Base result message with cost and usage information.
                                  BaseSystemMessage clawd_code_sdk.models.system_messages Base class for all system messages.
                                  ClaudeAgentOptions clawd_code_sdk.models.options Query options for Claude SDK.
                                  ClaudeCodeSettings clawd_code_sdk.models.settings Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings.
                                  ClaudeSDKClient clawd_code_sdk.client Client for bidirectional, interactive conversations with Claude Code.
                                  CommandHookHandler clawd_code_sdk.models.hooks
                                  ContinueLatest clawd_code_sdk.models.options Continue the most recent conversation.
                                  ConversationTurn clawd_code_sdk.session Collected result of a single send/receive cycle.
                                  Filesystem clawd_code_sdk.models.settings Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation.
                                  FromPR clawd_code_sdk.models.options Resume sessions linked to a specific GitHub PR.
                                  GetSettingsResponse clawd_code_sdk.models.control Response from get_settings() containing effective and per-source settings.
                                  HookContext clawd_code_sdk.models.hooks Context information for hook callbacks.
                                  HookMatcher clawd_code_sdk.models.hooks Hook matcher configuration.
                                  HookMatcherConfig clawd_code_sdk.models.hooks Declarative hook matcher for agent/skill/settings hook configuration.
                                  Hooks clawd_code_sdk.models.settings Lifecycle event hooks that run at configurable points during Claude Code operation (tool use, session start/end, notifications, prompt submit, message display, and more), not just before/after tool executions. See https://code.claude.com/docs/en/hooks.
                                  ImageBlock clawd_code_sdk.models.content_blocks Image content block (storage-only, not emitted on the wire).
                                  ImageSource clawd_code_sdk.models.content_blocks Base64-encoded image source data.
                                  InitSystemMessage clawd_code_sdk.models.system_messages System init message with session metadata.
                                  McpAuthenticateResponse clawd_code_sdk.models.control Response from authenticating with an MCP server.
                                  McpSdkServerConfig clawd_code_sdk.models.mcp SDK MCP server configuration (serializable, no instance).
                                  McpSdkServerConfigWithInstance clawd_code_sdk.models.mcp SDK MCP server config with a live McpServer instance. Not serializable.
                                  McpSetServersResult clawd_code_sdk.models.mcp Result of a setMcpServers operation.
                                  Network clawd_code_sdk.models.settings Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.
                                  NewSession clawd_code_sdk.models.options Start a fresh session.
                                  NotificationHookInput clawd_code_sdk.models.hooks Input data for Notification hook events.
                                  NotificationHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for Notification events.
                                  PermissionRequestHookInput clawd_code_sdk.models.hooks Input data for PermissionRequest hook events.
                                  PermissionRequestHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for PermissionRequest events.
                                  PermissionResultAllow clawd_code_sdk.models.permissions Allow permission result.
                                  PermissionResultDeny clawd_code_sdk.models.permissions Deny permission result.
                                  Permissions clawd_code_sdk.models.settings Tool usage permissions configuration.
                                  PostCompactHookInput clawd_code_sdk.models.hooks Input data for PostCompact hook events.
                                  PostToolUseFailureHookInput clawd_code_sdk.models.hooks Input data for PostToolUseFailure hook events.
                                  PostToolUseFailureHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for PostToolUseFailure events.
                                  PostToolUseHookInput clawd_code_sdk.models.hooks Input data for PostToolUse hook events.
                                  PreCompactHookInput clawd_code_sdk.models.hooks Input data for PreCompact hook events.
                                  PreToolUseHookInput clawd_code_sdk.models.hooks Input data for PreToolUse hook events.
                                  PromptHookHandler clawd_code_sdk.models.hooks LLM prompt hook handler.
                                  RemoteControlResponse clawd_code_sdk.models.control Response from enabling remote control.
                                  ResultErrorMessage clawd_code_sdk.models.messages Error result message.
                                  ResultSuccessMessage clawd_code_sdk.models.messages Successful result message.
                                  ResumeSession clawd_code_sdk.models.options Resume an existing session by ID.
                                  SDKSessionInfo clawd_code_sdk.models.session Session metadata returned by list_sessions.
                                  Sandbox clawd_code_sdk.models.settings Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing.
                                  SdkMcpTool clawd_code_sdk.mcp_utils Definition for an SDK MCP tool.
                                  SdkPluginConfig clawd_code_sdk.models.mcp SDK plugin configuration.
                                  Session clawd_code_sdk.session A managed Claude session wrapping a ClaudeSDKClient.
                                  SessionManager clawd_code_sdk.session Manages multiple concurrent Claude SDK sessions.
                                  SessionMessage clawd_code_sdk.models.session A message from a session transcript.
                                  SessionSnapshot clawd_code_sdk.session Read-only snapshot of session metadata at a point in time.
                                  SettingsSource clawd_code_sdk.models.control A single settings source with its raw settings.
                                  StopHookInput clawd_code_sdk.models.hooks Input data for Stop hook events.
                                  SubagentStartHookInput clawd_code_sdk.models.hooks Input data for SubagentStart hook events.
                                  SubagentStartHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for SubagentStart events.
                                  SubagentStopHookInput clawd_code_sdk.models.hooks Input data for SubagentStop hook events.
                                  TextBlock clawd_code_sdk.models.content_blocks Text content block.
                                  ThinkingBlock clawd_code_sdk.models.content_blocks Thinking/reasoning content block.
                                  ThinkingConfigAdaptive clawd_code_sdk.models.thinking Adaptive thinking configuration - model decides thinking budget.
                                  ThinkingConfigDisabled clawd_code_sdk.models.thinking Disabled thinking configuration.
                                  ThinkingConfigEnabled clawd_code_sdk.models.thinking Enabled thinking configuration with explicit token budget.
                                  ToolCallSummary clawd_code_sdk.session Summary of a single tool invocation within a conversation turn.
                                  ToolPermissionContext clawd_code_sdk.models.permissions Context information for tool permission callbacks.
                                  ToolResultBlock clawd_code_sdk.models.content_blocks Tool result content block.
                                  ToolUseBlock clawd_code_sdk.models.content_blocks Tool use content block.
                                  UserDocumentPrompt clawd_code_sdk.models.prompts A user prompt containing a base64-encoded PDF document.
                                  UserDocumentURLPrompt clawd_code_sdk.models.prompts A user prompt containing a PDF document referenced by URL.
                                  UserImagePrompt clawd_code_sdk.models.prompts A user prompt containing a single base64-encoded image.
                                  UserImageURLPrompt clawd_code_sdk.models.prompts A user prompt containing an image referenced by URL.
                                  UserMessage clawd_code_sdk.models.messages User message.
                                  UserPlainTextDocumentPrompt clawd_code_sdk.models.prompts A user prompt containing a plain text document.
                                  UserPromptSubmitHookInput clawd_code_sdk.models.hooks Input data for UserPromptSubmit hook events.
                                  UserTextPrompt clawd_code_sdk.models.prompts A text-only user prompt.

                                  🛈 DocStrings

                                  Claude SDK for Python.

                                  AgentHooksConfig module-attribute

                                  AgentHooksConfig = dict[HookEvent, list[HookMatcherConfig]]
                                  

                                  Type alias for the hooks field on AgentDefinition.

                                  Maps hook event names to lists of matcher configs. Example::

                                  hooks: AgentHooksConfig = {
                                      "PreToolUse": [
                                          {
                                              "matcher": "Bash",
                                              "hooks": [{"type": "command", "command": "./check.sh"}],
                                          }
                                      ],
                                  }
                                  

                                  CommandHookHandler module-attribute

                                  CommandHookHandler = TypedDict(
                                      "CommandHookHandler",
                                      {
                                          "type": Literal["command"],
                                          "command": str,
                                          "timeout": NotRequired[float],
                                          "async": NotRequired[bool],
                                          "statusMessage": NotRequired[str],
                                          "once": NotRequired[bool],
                                      },
                                  )
                                  

                                  Bash command hook handler.

                                  See https://code.claude.com/docs/en/hooks#command-hook-fields

                                  ContentBlock module-attribute

                                  ContentBlock = Annotated[
                                      TextBlock
                                      | ThinkingBlock
                                      | ToolUseBlock
                                      | ToolResultBlock
                                      | ImageBlock
                                      | DocumentBlock
                                      | ServerContentBlock,
                                      Discriminator("type"),
                                  ]
                                  

                                  All content block types (used for storage/JSONL which doesn't distinguish by role).

                                  HookHandler module-attribute

                                  Union of all declarative hook handler types.

                                  Message module-attribute

                                  Message = Annotated[
                                      Annotated[UserMessage, Tag("user")]
                                      | Annotated[AssistantMessage, Tag("assistant")]
                                      | Annotated[ResultSuccessMessage, Tag("result_success")]
                                      | Annotated[ResultErrorMessage, Tag("result_error")]
                                      | Annotated[StreamEvent, Tag("stream_event")]
                                      | Annotated[RateLimitMessage, Tag("rate_limit_event")]
                                      | Annotated[ToolProgressMessage, Tag("tool_progress")]
                                      | Annotated[ToolUseSummaryMessage, Tag("tool_use_summary")]
                                      | Annotated[AuthStatusMessage, Tag("auth_status")]
                                      | Annotated[PromptSuggestionMessage, Tag("prompt_suggestion")]
                                      | Annotated[ConversationResetMessage, Tag("conversation_reset")]
                                      | Annotated[CommandLifecycleMessage, Tag("command_lifecycle")]
                                      | Annotated[SystemMessageUnion, Tag("system")],
                                      Discriminator(_message_discriminator),
                                  ]
                                  

                                  Discriminated union of all wire-format message types.

                                  OnUserQuestion module-attribute

                                  OnUserQuestion = Callable[
                                      [AskUserQuestionInput, ToolPermissionContext], Awaitable[PermissionResult]
                                  ]
                                  

                                  Callback for handling AskUserQuestion elicitation requests.

                                  Called when Claude asks the user a clarifying question. The callback should return a PermissionResultAllow with updated_input containing the answers, or a PermissionResultDeny to cancel.

                                  SessionConfig module-attribute

                                  Union of all session configuration types.

                                  Can also be specified as a plain str, which is a shortcut for ResumeSession(session_id=str).

                                  UserPrompt module-attribute

                                  Union type for all user prompt dataclasses.

                                  APIError

                                  Bases: ClaudeSDKError

                                  Base exception for Anthropic API errors.

                                  This exception is raised when the API returns an error response that was previously returned as a text message. Subclasses provide more specific error types for programmatic handling.

                                  Attributes:

                                  Name Type Description
                                  error_type

                                  The type of API error (e.g., "rate_limit", "invalid_request").

                                  message

                                  The error message from the API.

                                  model

                                  The model that was being used when the error occurred.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class APIError(ClaudeSDKError):
                                      """Base exception for Anthropic API errors.
                                  
                                      This exception is raised when the API returns an error response that was
                                      previously returned as a text message. Subclasses provide more specific
                                      error types for programmatic handling.
                                  
                                      Attributes:
                                          error_type: The type of API error (e.g., "rate_limit", "invalid_request").
                                          message: The error message from the API.
                                          model: The model that was being used when the error occurred.
                                      """
                                  
                                      def __init__(
                                          self,
                                          message: str,
                                          error_type: APIErrorType,
                                          model: Model | None = None,
                                      ) -> None:
                                          self.error_type = error_type
                                          self.model = model
                                          super().__init__(message)
                                  

                                  AgentDefinition

                                  Bases: ClaudeCodeBaseModel

                                  User-facing agent definition configuration.

                                  Accepts ergonomic Python inputs (e.g. dict-style mcp_servers) and converts to the wire format via to_wire().

                                  Source code in src/clawd_code_sdk/models/agents.py
                                  class AgentDefinition(ClaudeCodeBaseModel):
                                      """User-facing agent definition configuration.
                                  
                                      Accepts ergonomic Python inputs (e.g. dict-style mcp_servers)
                                      and converts to the wire format via ``to_wire()``.
                                      """
                                  
                                      description: str = Field(..., title="Agent Description", examples=["QA Assistant"])
                                      """A brief description of the agent's purpose."""
                                  
                                      prompt: str = Field(..., title="Agent Prompt", examples=["Do XY"])
                                      """The prompt to use for this agent."""
                                  
                                      tools: list[ToolName | str] | None = Field(default=None, title="Agent Tools", examples=["Bash"])
                                      """The tools this agent has access to."""
                                  
                                      model: ModelName | Literal["inherit"] | str | None = Field(  # noqa: PYI051
                                          default=None,
                                          title="Agent Model",
                                          examples=["sonnet"],
                                      )
                                      """The model to use for this agent."""
                                  
                                      memory: SettingSource | None = Field(
                                          default=None,
                                          title="Agent Memory",
                                          examples=["user", "project"],
                                      )
                                      """Persistent cross-session memory scope for this agent."""
                                      mcp_servers: Mapping[str, McpServerConfigForProcessTransport | None] | None = None
                                      """MCP servers for this agent.
                                  
                                      Maps server names to configs. Use ``None`` as the value to reference
                                      a server already configured in settings::
                                      """
                                  
                                      disallowed_tools: list[ToolName | str] | None = Field(
                                          default=None,
                                          title="Disallowed Tools",
                                          examples=["Bash"],
                                      )
                                      """Tools this agent is not allowed to use."""
                                  
                                      critical_system_reminder_experimental: str | None = Field(
                                          default=None,
                                          title="Critical System Reminder",
                                          alias="criticalSystemReminder_EXPERIMENTAL",
                                      )
                                      """Critical system reminder message to display to the user."""
                                  
                                      skills: list[str] | None = Field(default=None, title="Skills", examples=["my-skill"])
                                      """Skills this agent has."""
                                  
                                      initial_prompt: str | None = Field(default=None, title="Initial Prompt")
                                      """Auto-submitted as the first user turn when this agent is the main thread agent.
                                  
                                      Slash commands are processed. Prepended to any user-provided prompt.
                                      """
                                  
                                      max_turns: int | None = Field(default=None, title="Max Turns")
                                      """Maximum number of agentic turns (API round-trips) before stopping."""
                                  
                                      background: bool | None = Field(default=None, title="Run in Background")
                                      """Whether this agent runs in the background."""
                                  
                                      hooks: AgentHooksConfig | None = Field(default=None, title="Agent Hooks")
                                      """Hook configurations for this agent."""
                                  
                                      effort: ReasoningEffort | int | None = Field(
                                          default=None,
                                          title="Reasoning effort",
                                          examples=["high"],
                                      )
                                      """Effort level for thinking depth."""
                                  
                                      permission_mode: PermissionMode | None = Field(
                                          default=None,
                                          title="Permission Mode",
                                          examples=["bypassPermissions"],
                                      )
                                      """Permission mode for this agent."""
                                  
                                      isolation: Literal["worktree"] | None = Field(
                                          default=None,
                                          title="Isolation Mode",
                                          examples=["worktree"],
                                      )
                                      """Isolation mode. ``"worktree"`` runs the agent in a separate git worktree."""
                                  
                                      auto_compact_window: int | None = Field(default=None, title="Auto-Compact Window")
                                      """Token count at which this agent compacts its own conversation as a subagent.
                                  
                                      Only lowers the inherited window. No effect on the main session agent."""
                                  
                                      omit_claude_md: bool | None = Field(default=None, title="Omit CLAUDE.md")
                                      """Run without user/project/local CLAUDE.md files when running as a subagent."""
                                  
                                      observer: str | None = Field(default=None, title="Observer Agent")
                                      """Agent type(s) (comma-separated, max 4) auto-spawned as background observers."""
                                  
                                      observer_message: str | None = Field(default=None, title="Observer Message")
                                      """Supplemental postamble appended to each activity digest sent to the observer."""
                                  
                                      def to_wire(self) -> dict[str, Any]:
                                          """Serialize to the wire-format dict for the CLI control protocol.
                                  
                                          Converts dict-style mcp_servers to the array format the CLI expects:
                                          ``{"git": config}`` -> ``[{"git": config}]``
                                  
                                          Returns a camelCase dict with None values excluded.
                                          """
                                          model = self.to_wire_model()
                                          return model.model_dump(by_alias=True, exclude_none=True)
                                  
                                      def to_wire_model(self) -> AgentWireDefinition:
                                          """Serialize to the wire-format dict for the CLI control protocol.
                                  
                                          Converts dict-style mcp_servers to the array format the CLI expects:
                                          ``{"git": config}`` -> ``[{"git": config}]``
                                  
                                          Returns a camelCase dict with None values excluded.
                                          """
                                          mcp = [
                                              name if config is None else {name: config}
                                              for name, config in (self.mcp_servers or {}).items()
                                          ]
                                          return AgentWireDefinition(
                                              description=self.description,
                                              prompt=self.prompt,
                                              tools=self.tools,
                                              model=self.model,
                                              memory=self.memory,
                                              mcp_servers=mcp or None,
                                              disallowed_tools=self.disallowed_tools,
                                              critical_system_reminder_experimental=self.critical_system_reminder_experimental,
                                              skills=self.skills,
                                              initial_prompt=self.initial_prompt,
                                              max_turns=self.max_turns,
                                              background=self.background,
                                              hooks=self.hooks,
                                              effort=self.effort,
                                              permission_mode=self.permission_mode,
                                              isolation=self.isolation,
                                              auto_compact_window=self.auto_compact_window,
                                              omit_claude_md=self.omit_claude_md,
                                              observer=self.observer,
                                              observer_message=self.observer_message,
                                          )
                                  

                                  auto_compact_window class-attribute instance-attribute

                                  auto_compact_window: int | None = Field(default=None, title='Auto-Compact Window')
                                  

                                  Token count at which this agent compacts its own conversation as a subagent.

                                  Only lowers the inherited window. No effect on the main session agent.

                                  background class-attribute instance-attribute

                                  background: bool | None = Field(default=None, title='Run in Background')
                                  

                                  Whether this agent runs in the background.

                                  critical_system_reminder_experimental class-attribute instance-attribute

                                  critical_system_reminder_experimental: str | None = Field(
                                      default=None, title="Critical System Reminder", alias="criticalSystemReminder_EXPERIMENTAL"
                                  )
                                  

                                  Critical system reminder message to display to the user.

                                  description class-attribute instance-attribute

                                  description: str = Field(..., title='Agent Description', examples=['QA Assistant'])
                                  

                                  A brief description of the agent's purpose.

                                  disallowed_tools class-attribute instance-attribute

                                  disallowed_tools: list[ToolName | str] | None = Field(
                                      default=None, title="Disallowed Tools", examples=["Bash"]
                                  )
                                  

                                  Tools this agent is not allowed to use.

                                  effort class-attribute instance-attribute

                                  effort: ReasoningEffort | int | None = Field(
                                      default=None, title="Reasoning effort", examples=["high"]
                                  )
                                  

                                  Effort level for thinking depth.

                                  hooks class-attribute instance-attribute

                                  hooks: AgentHooksConfig | None = Field(default=None, title='Agent Hooks')
                                  

                                  Hook configurations for this agent.

                                  initial_prompt class-attribute instance-attribute

                                  initial_prompt: str | None = Field(default=None, title='Initial Prompt')
                                  

                                  Auto-submitted as the first user turn when this agent is the main thread agent.

                                  Slash commands are processed. Prepended to any user-provided prompt.

                                  isolation class-attribute instance-attribute

                                  isolation: Literal["worktree"] | None = Field(
                                      default=None, title="Isolation Mode", examples=["worktree"]
                                  )
                                  

                                  Isolation mode. "worktree" runs the agent in a separate git worktree.

                                  max_turns class-attribute instance-attribute

                                  max_turns: int | None = Field(default=None, title='Max Turns')
                                  

                                  Maximum number of agentic turns (API round-trips) before stopping.

                                  mcp_servers class-attribute instance-attribute

                                  mcp_servers: Mapping[str, McpServerConfigForProcessTransport | None] | None = None
                                  

                                  MCP servers for this agent.

                                  Maps server names to configs. Use None as the value to reference a server already configured in settings::

                                  memory class-attribute instance-attribute

                                  memory: SettingSource | None = Field(
                                      default=None, title="Agent Memory", examples=["user", "project"]
                                  )
                                  

                                  Persistent cross-session memory scope for this agent.

                                  model class-attribute instance-attribute

                                  model: ModelName | Literal["inherit"] | str | None = Field(
                                      default=None, title="Agent Model", examples=["sonnet"]
                                  )
                                  

                                  The model to use for this agent.

                                  observer class-attribute instance-attribute

                                  observer: str | None = Field(default=None, title='Observer Agent')
                                  

                                  Agent type(s) (comma-separated, max 4) auto-spawned as background observers.

                                  observer_message class-attribute instance-attribute

                                  observer_message: str | None = Field(default=None, title='Observer Message')
                                  

                                  Supplemental postamble appended to each activity digest sent to the observer.

                                  omit_claude_md class-attribute instance-attribute

                                  omit_claude_md: bool | None = Field(default=None, title='Omit CLAUDE.md')
                                  

                                  Run without user/project/local CLAUDE.md files when running as a subagent.

                                  permission_mode class-attribute instance-attribute

                                  permission_mode: PermissionMode | None = Field(
                                      default=None, title="Permission Mode", examples=["bypassPermissions"]
                                  )
                                  

                                  Permission mode for this agent.

                                  prompt class-attribute instance-attribute

                                  prompt: str = Field(..., title='Agent Prompt', examples=['Do XY'])
                                  

                                  The prompt to use for this agent.

                                  skills class-attribute instance-attribute

                                  skills: list[str] | None = Field(default=None, title='Skills', examples=['my-skill'])
                                  

                                  Skills this agent has.

                                  tools class-attribute instance-attribute

                                  tools: list[ToolName | str] | None = Field(default=None, title='Agent Tools', examples=['Bash'])
                                  

                                  The tools this agent has access to.

                                  to_wire

                                  to_wire() -> dict[str, Any]
                                  

                                  Serialize to the wire-format dict for the CLI control protocol.

                                  Converts dict-style mcp_servers to the array format the CLI expects: {"git": config} -> [{"git": config}]

                                  Returns a camelCase dict with None values excluded.

                                  Source code in src/clawd_code_sdk/models/agents.py
                                  def to_wire(self) -> dict[str, Any]:
                                      """Serialize to the wire-format dict for the CLI control protocol.
                                  
                                      Converts dict-style mcp_servers to the array format the CLI expects:
                                      ``{"git": config}`` -> ``[{"git": config}]``
                                  
                                      Returns a camelCase dict with None values excluded.
                                      """
                                      model = self.to_wire_model()
                                      return model.model_dump(by_alias=True, exclude_none=True)
                                  

                                  to_wire_model

                                  to_wire_model() -> AgentWireDefinition
                                  

                                  Serialize to the wire-format dict for the CLI control protocol.

                                  Converts dict-style mcp_servers to the array format the CLI expects: {"git": config} -> [{"git": config}]

                                  Returns a camelCase dict with None values excluded.

                                  Source code in src/clawd_code_sdk/models/agents.py
                                  def to_wire_model(self) -> AgentWireDefinition:
                                      """Serialize to the wire-format dict for the CLI control protocol.
                                  
                                      Converts dict-style mcp_servers to the array format the CLI expects:
                                      ``{"git": config}`` -> ``[{"git": config}]``
                                  
                                      Returns a camelCase dict with None values excluded.
                                      """
                                      mcp = [
                                          name if config is None else {name: config}
                                          for name, config in (self.mcp_servers or {}).items()
                                      ]
                                      return AgentWireDefinition(
                                          description=self.description,
                                          prompt=self.prompt,
                                          tools=self.tools,
                                          model=self.model,
                                          memory=self.memory,
                                          mcp_servers=mcp or None,
                                          disallowed_tools=self.disallowed_tools,
                                          critical_system_reminder_experimental=self.critical_system_reminder_experimental,
                                          skills=self.skills,
                                          initial_prompt=self.initial_prompt,
                                          max_turns=self.max_turns,
                                          background=self.background,
                                          hooks=self.hooks,
                                          effort=self.effort,
                                          permission_mode=self.permission_mode,
                                          isolation=self.isolation,
                                          auto_compact_window=self.auto_compact_window,
                                          omit_claude_md=self.omit_claude_md,
                                          observer=self.observer,
                                          observer_message=self.observer_message,
                                      )
                                  

                                  AgentHookHandler

                                  Bases: TypedDict

                                  Agent hook handler with multi-turn tool access.

                                  See https://code.claude.com/docs/en/hooks#agent-based-hooks

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class AgentHookHandler(TypedDict):
                                      """Agent hook handler with multi-turn tool access.
                                  
                                      See https://code.claude.com/docs/en/hooks#agent-based-hooks
                                      """
                                  
                                      type: Literal["agent"]
                                      prompt: str
                                      model: NotRequired[str]
                                      timeout: NotRequired[float]
                                      statusMessage: NotRequired[str]
                                  

                                  AppliedSettings

                                  Bases: BaseModel

                                  The currently applied model and effort settings.

                                  Source code in src/clawd_code_sdk/models/control.py
                                  class AppliedSettings(BaseModel):
                                      """The currently applied model and effort settings."""
                                  
                                      model: ModelName | str
                                      """The active model identifier."""
                                  
                                      effort: EffortLevel | None = None
                                      """The active effort level, or None if not set."""
                                  

                                  effort class-attribute instance-attribute

                                  effort: EffortLevel | None = None
                                  

                                  The active effort level, or None if not set.

                                  model instance-attribute

                                  model: ModelName | str
                                  

                                  The active model identifier.

                                  AssistantMessage

                                  Bases: BaseModel

                                  Assistant message with content blocks.

                                  Source code in src/clawd_code_sdk/models/messages.py
                                  class AssistantMessage(BaseModel):
                                      """Assistant message with content blocks."""
                                  
                                      model_config = ConfigDict(extra="forbid" if IS_DEV else "ignore", arbitrary_types_allowed=True)
                                  
                                      type: Literal["assistant"] = "assistant"
                                      message: AssistantMessageContent
                                      parent_tool_use_id: str | None = None
                                      error: AssistantMessageError | None = None
                                      session_id: str | None = None
                                      uuid: str | None = None
                                      request_id: str | None = None
                                      """API request ID that produced this message."""
                                      user_message_uuid: str | None = None
                                      """UUID of the user message this assistant message responds to."""
                                      user_message_uuids: list[str] | None = None
                                      """UUIDs of all user messages this assistant message responds to (batched turns)."""
                                      resume_reason: str | None = None
                                      resumed_from_incomplete_thinking: bool | None = None
                                      supersedes: list[str] | None = None
                                      """UUIDs of previously emitted assistant messages this one replaces."""
                                      aborted: bool | None = None
                                      """Set when the turn was aborted while this message was streaming."""
                                      agent_id: str | None = None
                                      subagent_type: str | None = None
                                      task_description: str | None = None
                                      timestamp: str | None = None
                                      context_usage: SDKContextUsage | None = None
                                      usage_report: SDKUsageReport | None = None
                                      wire_tool_inputs: dict[str, dict[str, Any]] | None = None
                                      """Tool inputs as sent on the wire, keyed by tool_use ID (undocumented)."""
                                      wire_ingest_context: dict[str, dict[str, Any]] | None = None
                                      """Per-tool_use ingest context (e.g. cwd), keyed by tool_use ID (undocumented)."""
                                      thinking_duration_ms: float | None = None
                                      """How long the model spent thinking for this message (undocumented)."""
                                      thinking_display: str | None = None
                                      """Active thinking display mode (undocumented)."""
                                      tool_use_meta: list[ToolUseMeta] | None = None
                                      """Display metadata for the tool_use blocks in this message (undocumented)."""
                                      is_api_error_message: bool | None = None
                                      """True when this assistant message wraps an API error (undocumented)."""
                                      api_error_status: int | None = None
                                      """HTTP status code of the API error when `is_api_error_message` is true."""
                                      api_error_type: str | None = None
                                      """The `error.type` of the API error response body, e.g. `rate_limit_error`."""
                                      api_error_origin: Literal["first_party"] | None = None
                                      """`first_party` when Anthropic's own API sent the error response."""
                                      api_error_params: ApiErrorParams | None = None
                                      """Parameters of the API error, for the error kinds that have any."""
                                  
                                      @property
                                      def content(self) -> Sequence[AssistantContentBlock]:
                                          """Return the message content blocks."""
                                          return self.message.content
                                  
                                      @property
                                      def model(self) -> str:
                                          """Return the model name."""
                                          return self.message.model
                                  
                                      def raise_if_api_error(self) -> None:
                                          """Raise the appropriate API exception if error is set."""
                                          if self.error is None:
                                              return
                                          error_message = next(
                                              (block.text for block in self.content if isinstance(block, TextBlock)),
                                              "An API error occurred",
                                          )
                                          match self.error:
                                              case "authentication_failed":
                                                  raise AuthenticationError(error_message, self.model)
                                              case "billing_error":
                                                  raise BillingError(error_message, self.model)
                                              case "rate_limit" | "overloaded":
                                                  raise RateLimitError(error_message, self.model)
                                              case "invalid_request":
                                                  raise InvalidRequestError(error_message, self.model)
                                              case "server_error":
                                                  raise ServerError(error_message, self.model)
                                              case "oauth_org_not_allowed" | "account_on_hold" | "verification_required":
                                                  raise AuthenticationError(error_message, self.model)
                                              case "model_not_found":
                                                  raise InvalidRequestError(error_message, self.model)
                                              case _ as unknown:
                                                  raise APIError(error_message, unknown, self.model)
                                  
                                      def to_otel(self) -> OutputMessage:
                                          """Convert SDK content block objects into semconv OutputMessages."""
                                          from logfire._internal.integrations.llm_providers.semconv import OutputMessage
                                  
                                          from clawd_code_sdk.models.content_blocks import is_server_block, server_block_to_otel
                                  
                                          parts: list[MessagePart] = []
                                          for block in self.content:
                                              if is_server_block(block):
                                                  if (part := server_block_to_otel(block)) is not None:
                                                      parts.append(part)
                                              else:
                                                  parts.append(block.to_otel())
                                          return OutputMessage(role="assistant", parts=parts)
                                  

                                  aborted class-attribute instance-attribute

                                  aborted: bool | None = None
                                  

                                  Set when the turn was aborted while this message was streaming.

                                  api_error_origin class-attribute instance-attribute

                                  api_error_origin: Literal['first_party'] | None = None
                                  

                                  first_party when Anthropic's own API sent the error response.

                                  api_error_params class-attribute instance-attribute

                                  api_error_params: ApiErrorParams | None = None
                                  

                                  Parameters of the API error, for the error kinds that have any.

                                  api_error_status class-attribute instance-attribute

                                  api_error_status: int | None = None
                                  

                                  HTTP status code of the API error when is_api_error_message is true.

                                  api_error_type class-attribute instance-attribute

                                  api_error_type: str | None = None
                                  

                                  The error.type of the API error response body, e.g. rate_limit_error.

                                  content property

                                  content: Sequence[AssistantContentBlock]
                                  

                                  Return the message content blocks.

                                  is_api_error_message class-attribute instance-attribute

                                  is_api_error_message: bool | None = None
                                  

                                  True when this assistant message wraps an API error (undocumented).

                                  model property

                                  model: str
                                  

                                  Return the model name.

                                  request_id class-attribute instance-attribute

                                  request_id: str | None = None
                                  

                                  API request ID that produced this message.

                                  supersedes class-attribute instance-attribute

                                  supersedes: list[str] | None = None
                                  

                                  UUIDs of previously emitted assistant messages this one replaces.

                                  thinking_display class-attribute instance-attribute

                                  thinking_display: str | None = None
                                  

                                  Active thinking display mode (undocumented).

                                  thinking_duration_ms class-attribute instance-attribute

                                  thinking_duration_ms: float | None = None
                                  

                                  How long the model spent thinking for this message (undocumented).

                                  tool_use_meta class-attribute instance-attribute

                                  tool_use_meta: list[ToolUseMeta] | None = None
                                  

                                  Display metadata for the tool_use blocks in this message (undocumented).

                                  user_message_uuid class-attribute instance-attribute

                                  user_message_uuid: str | None = None
                                  

                                  UUID of the user message this assistant message responds to.

                                  user_message_uuids class-attribute instance-attribute

                                  user_message_uuids: list[str] | None = None
                                  

                                  UUIDs of all user messages this assistant message responds to (batched turns).

                                  wire_ingest_context class-attribute instance-attribute

                                  wire_ingest_context: dict[str, dict[str, Any]] | None = None
                                  

                                  Per-tool_use ingest context (e.g. cwd), keyed by tool_use ID (undocumented).

                                  wire_tool_inputs class-attribute instance-attribute

                                  wire_tool_inputs: dict[str, dict[str, Any]] | None = None
                                  

                                  Tool inputs as sent on the wire, keyed by tool_use ID (undocumented).

                                  raise_if_api_error

                                  raise_if_api_error() -> None
                                  

                                  Raise the appropriate API exception if error is set.

                                  Source code in src/clawd_code_sdk/models/messages.py
                                  def raise_if_api_error(self) -> None:
                                      """Raise the appropriate API exception if error is set."""
                                      if self.error is None:
                                          return
                                      error_message = next(
                                          (block.text for block in self.content if isinstance(block, TextBlock)),
                                          "An API error occurred",
                                      )
                                      match self.error:
                                          case "authentication_failed":
                                              raise AuthenticationError(error_message, self.model)
                                          case "billing_error":
                                              raise BillingError(error_message, self.model)
                                          case "rate_limit" | "overloaded":
                                              raise RateLimitError(error_message, self.model)
                                          case "invalid_request":
                                              raise InvalidRequestError(error_message, self.model)
                                          case "server_error":
                                              raise ServerError(error_message, self.model)
                                          case "oauth_org_not_allowed" | "account_on_hold" | "verification_required":
                                              raise AuthenticationError(error_message, self.model)
                                          case "model_not_found":
                                              raise InvalidRequestError(error_message, self.model)
                                          case _ as unknown:
                                              raise APIError(error_message, unknown, self.model)
                                  

                                  to_otel

                                  to_otel() -> OutputMessage
                                  

                                  Convert SDK content block objects into semconv OutputMessages.

                                  Source code in src/clawd_code_sdk/models/messages.py
                                  def to_otel(self) -> OutputMessage:
                                      """Convert SDK content block objects into semconv OutputMessages."""
                                      from logfire._internal.integrations.llm_providers.semconv import OutputMessage
                                  
                                      from clawd_code_sdk.models.content_blocks import is_server_block, server_block_to_otel
                                  
                                      parts: list[MessagePart] = []
                                      for block in self.content:
                                          if is_server_block(block):
                                              if (part := server_block_to_otel(block)) is not None:
                                                  parts.append(part)
                                          else:
                                              parts.append(block.to_otel())
                                      return OutputMessage(role="assistant", parts=parts)
                                  

                                  AuthenticationError

                                  Bases: APIError

                                  Raised when API authentication fails (401).

                                  This typically indicates an invalid API key or insufficient permissions.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class AuthenticationError(APIError):
                                      """Raised when API authentication fails (401).
                                  
                                      This typically indicates an invalid API key or insufficient permissions.
                                      """
                                  
                                      def __init__(self, message: str, model: Model | None = None) -> None:
                                          super().__init__(message, "authentication_failed", model)
                                  

                                  BaseHookInput

                                  Bases: TypedDict

                                  Base hook input fields present across many hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class BaseHookInput(TypedDict):
                                      """Base hook input fields present across many hook events."""
                                  
                                      session_id: str
                                      transcript_path: str
                                      cwd: str
                                      prompt_id: NotRequired[str]
                                      """ID of the user prompt that started the current turn."""
                                      permission_mode: NotRequired[str]
                                      effort: NotRequired[HookEffort]
                                  

                                  prompt_id instance-attribute

                                  prompt_id: NotRequired[str]
                                  

                                  ID of the user prompt that started the current turn.

                                  BaseResultMessage

                                  Bases: BaseMessage

                                  Base result message with cost and usage information.

                                  Note: Fields use inconsistent scoping. See per-field docs for details.

                                  Source code in src/clawd_code_sdk/models/messages.py
                                  class BaseResultMessage(BaseMessage):
                                      """Base result message with cost and usage information.
                                  
                                      Note: Fields use inconsistent scoping. See per-field docs for details.
                                      """
                                  
                                      type: Literal["result"] = "result"
                                      session_id: str
                                      duration_ms: int
                                      """Wall-clock time for this query only (per-query)."""
                                      duration_api_ms: int
                                      """Cumulative API time across the entire session."""
                                      is_error: bool
                                      num_turns: int
                                      """Number of model turns in this query only (per-query)."""
                                      total_cost_usd: float
                                      """Cumulative cost across the entire session."""
                                      usage: Usage
                                      """Token usage from the last API call only (per-turn)."""
                                      stop_reason: StopReason | None
                                      model_usage: dict[str, ModelUsage] = Field(default_factory=dict, validation_alias="modelUsage")
                                      """Cumulative token usage per model across the entire session."""
                                      permission_denials: list[SDKPermissionDenial] = []
                                      """Permission denials from the last API call only (per-turn)."""
                                      fast_mode_state: FastModeState | None = None
                                      """Whether fast mode was enabled."""
                                      terminal_reason: TerminalReason | None = None
                                      """Why the query loop terminated.
                                  
                                      Unset when the loop was bypassed (local slash command) or interrupted externally
                                      (budget/retry limits checked between yields).
                                      """
                                      fast_mode_disabled_reason: FastModeDisabledReason | None = None
                                      queued_turn_count: int | None = None
                                      """Number of turns still queued after this result."""
                                      user_message_uuid: str | None = None
                                      """UUID of the user message that started this turn."""
                                      user_message_uuids: list[str] | None = None
                                      """UUIDs of all user messages handled in this turn."""
                                      begun_message_ids: list[str] | None = None
                                      """API message IDs (``msg_...``) the turn began (undocumented, CLI 2.1.330+)."""
                                      resume_reason: str | None = None
                                      result_index: int | None = None
                                      credential_expires_at: str | None = None
                                      origin: SDKMessageOrigin | None = None
                                      model_usage_since_last_result: dict[str, ModelUsage] | None = None
                                      """Per-model usage accrued since the previous result (undocumented)."""
                                      process_turn_index: int | None = None
                                      """Index of this turn within the CLI process (undocumented)."""
                                      safety_stops: int | None = None
                                      """Number of safety stops during the turn (undocumented)."""
                                      subagent_stats: SubagentStats | None = None
                                      """Subagent statistics for the turn (undocumented)."""
                                      turn_start_resume_kind: str | None = None
                                      """How the turn started relative to a resume, e.g. "none" (undocumented)."""
                                      # Timing diagnostics (undocumented; maps of phase name -> milliseconds/counters)
                                      time_to_request_cpu_ms: float | None = None
                                      time_to_request_loop_lag_ms: float | None = None
                                      time_to_request_major_faults: int | None = None
                                      time_to_request_phases_ms: dict[str, float] | None = None
                                      input_attachments_detail: dict[str, float | str] | None = None
                                      tool_schema_build_detail: dict[str, float] | None = None
                                      message_normalization_detail: dict[str, float] | None = None
                                      request_build_detail: dict[str, float] | None = None
                                  

                                  begun_message_ids class-attribute instance-attribute

                                  begun_message_ids: list[str] | None = None
                                  

                                  API message IDs (msg_...) the turn began (undocumented, CLI 2.1.330+).

                                  duration_api_ms instance-attribute

                                  duration_api_ms: int
                                  

                                  Cumulative API time across the entire session.

                                  duration_ms instance-attribute

                                  duration_ms: int
                                  

                                  Wall-clock time for this query only (per-query).

                                  fast_mode_state class-attribute instance-attribute

                                  fast_mode_state: FastModeState | None = None
                                  

                                  Whether fast mode was enabled.

                                  model_usage class-attribute instance-attribute

                                  model_usage: dict[str, ModelUsage] = Field(default_factory=dict, validation_alias='modelUsage')
                                  

                                  Cumulative token usage per model across the entire session.

                                  model_usage_since_last_result class-attribute instance-attribute

                                  model_usage_since_last_result: dict[str, ModelUsage] | None = None
                                  

                                  Per-model usage accrued since the previous result (undocumented).

                                  num_turns instance-attribute

                                  num_turns: int
                                  

                                  Number of model turns in this query only (per-query).

                                  permission_denials class-attribute instance-attribute

                                  permission_denials: list[SDKPermissionDenial] = []
                                  

                                  Permission denials from the last API call only (per-turn).

                                  process_turn_index class-attribute instance-attribute

                                  process_turn_index: int | None = None
                                  

                                  Index of this turn within the CLI process (undocumented).

                                  queued_turn_count class-attribute instance-attribute

                                  queued_turn_count: int | None = None
                                  

                                  Number of turns still queued after this result.

                                  safety_stops class-attribute instance-attribute

                                  safety_stops: int | None = None
                                  

                                  Number of safety stops during the turn (undocumented).

                                  subagent_stats class-attribute instance-attribute

                                  subagent_stats: SubagentStats | None = None
                                  

                                  Subagent statistics for the turn (undocumented).

                                  terminal_reason class-attribute instance-attribute

                                  terminal_reason: TerminalReason | None = None
                                  

                                  Why the query loop terminated.

                                  Unset when the loop was bypassed (local slash command) or interrupted externally (budget/retry limits checked between yields).

                                  total_cost_usd instance-attribute

                                  total_cost_usd: float
                                  

                                  Cumulative cost across the entire session.

                                  turn_start_resume_kind class-attribute instance-attribute

                                  turn_start_resume_kind: str | None = None
                                  

                                  How the turn started relative to a resume, e.g. "none" (undocumented).

                                  usage instance-attribute

                                  usage: Usage
                                  

                                  Token usage from the last API call only (per-turn).

                                  user_message_uuid class-attribute instance-attribute

                                  user_message_uuid: str | None = None
                                  

                                  UUID of the user message that started this turn.

                                  user_message_uuids class-attribute instance-attribute

                                  user_message_uuids: list[str] | None = None
                                  

                                  UUIDs of all user messages handled in this turn.

                                  BaseSystemMessage

                                  Bases: BaseModel

                                  Base class for all system messages.

                                  Source code in src/clawd_code_sdk/models/system_messages.py
                                  class BaseSystemMessage(BaseModel):
                                      """Base class for all system messages."""
                                  
                                      model_config = ConfigDict(extra="forbid" if IS_DEV else "ignore")
                                  
                                      type: Literal["system"] = "system"
                                      uuid: str
                                      session_id: str
                                  

                                  BillingError

                                  Bases: APIError

                                  Raised when there's a billing issue with the API account.

                                  This may indicate insufficient credits, expired subscription, or other billing-related issues.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class BillingError(APIError):
                                      """Raised when there's a billing issue with the API account.
                                  
                                      This may indicate insufficient credits, expired subscription, or other
                                      billing-related issues.
                                      """
                                  
                                      def __init__(self, message: str, model: Model | None = None) -> None:
                                          super().__init__(message, "billing_error", model)
                                  

                                  CLIConnectionError

                                  Bases: ClaudeSDKError

                                  Raised when unable to connect to Claude Code.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class CLIConnectionError(ClaudeSDKError):
                                      """Raised when unable to connect to Claude Code."""
                                  

                                  CLIJSONDecodeError

                                  Bases: ClaudeSDKError

                                  Raised when unable to decode JSON from CLI output.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class CLIJSONDecodeError(ClaudeSDKError):
                                      """Raised when unable to decode JSON from CLI output."""
                                  
                                      def __init__(self, line: str, original_error: Exception) -> None:
                                          self.line = line
                                          self.original_error = original_error
                                          super().__init__(f"Failed to decode JSON: {line[:100]}...")
                                  

                                  CLINotFoundError

                                  Bases: CLIConnectionError

                                  Raised when Claude Code is not found or not installed.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class CLINotFoundError(CLIConnectionError):
                                      """Raised when Claude Code is not found or not installed."""
                                  
                                      def __init__(self, message: str = "Claude Code not found", cli_path: str | None = None) -> None:
                                          if cli_path:
                                              message = f"{message}: {cli_path}"
                                          super().__init__(message)
                                  

                                  CanUseToolShadowedWarning

                                  Bases: UserWarning

                                  on_permission is a callback, but some tool calls are auto-approved before it runs.

                                  Emitted on connect. The TypeScript SDK reports the same condition as a process warning with code CLAUDE_SDK_CAN_USE_TOOL_SHADOWED. Suppress it with warnings.filterwarnings("ignore", category=CanUseToolShadowedWarning).

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class CanUseToolShadowedWarning(UserWarning):
                                      """``on_permission`` is a callback, but some tool calls are auto-approved before it runs.
                                  
                                      Emitted on connect. The TypeScript SDK reports the same condition as a process warning
                                      with code ``CLAUDE_SDK_CAN_USE_TOOL_SHADOWED``. Suppress it with
                                      ``warnings.filterwarnings("ignore", category=CanUseToolShadowedWarning)``.
                                      """
                                  

                                  ClaudeAgentOptions dataclass

                                  Query options for Claude SDK.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  120
                                  121
                                  122
                                  123
                                  124
                                  125
                                  126
                                  127
                                  128
                                  129
                                  130
                                  131
                                  132
                                  133
                                  134
                                  135
                                  136
                                  137
                                  138
                                  139
                                  140
                                  141
                                  142
                                  143
                                  144
                                  145
                                  146
                                  147
                                  148
                                  149
                                  150
                                  151
                                  152
                                  153
                                  154
                                  155
                                  156
                                  157
                                  158
                                  159
                                  160
                                  161
                                  162
                                  163
                                  164
                                  165
                                  166
                                  167
                                  168
                                  169
                                  170
                                  171
                                  172
                                  173
                                  174
                                  175
                                  176
                                  177
                                  178
                                  179
                                  180
                                  181
                                  182
                                  183
                                  184
                                  185
                                  186
                                  187
                                  188
                                  189
                                  190
                                  191
                                  192
                                  193
                                  194
                                  195
                                  196
                                  197
                                  198
                                  199
                                  200
                                  201
                                  202
                                  203
                                  204
                                  205
                                  206
                                  207
                                  208
                                  209
                                  210
                                  211
                                  212
                                  213
                                  214
                                  215
                                  216
                                  217
                                  218
                                  219
                                  220
                                  221
                                  222
                                  223
                                  224
                                  225
                                  226
                                  227
                                  228
                                  229
                                  230
                                  231
                                  232
                                  233
                                  234
                                  235
                                  236
                                  237
                                  238
                                  239
                                  240
                                  241
                                  242
                                  243
                                  244
                                  245
                                  246
                                  247
                                  248
                                  249
                                  250
                                  251
                                  252
                                  253
                                  254
                                  255
                                  256
                                  257
                                  258
                                  259
                                  260
                                  261
                                  262
                                  263
                                  264
                                  265
                                  266
                                  267
                                  268
                                  269
                                  270
                                  271
                                  272
                                  273
                                  274
                                  275
                                  276
                                  277
                                  278
                                  279
                                  280
                                  281
                                  282
                                  283
                                  284
                                  285
                                  286
                                  287
                                  288
                                  289
                                  290
                                  291
                                  292
                                  293
                                  294
                                  295
                                  296
                                  297
                                  298
                                  299
                                  300
                                  301
                                  302
                                  303
                                  304
                                  305
                                  306
                                  307
                                  308
                                  309
                                  310
                                  311
                                  312
                                  313
                                  314
                                  315
                                  316
                                  317
                                  318
                                  319
                                  320
                                  321
                                  322
                                  323
                                  324
                                  325
                                  326
                                  327
                                  328
                                  329
                                  330
                                  331
                                  332
                                  333
                                  334
                                  335
                                  336
                                  337
                                  338
                                  339
                                  340
                                  341
                                  342
                                  343
                                  344
                                  345
                                  346
                                  347
                                  348
                                  349
                                  350
                                  351
                                  352
                                  353
                                  354
                                  355
                                  356
                                  357
                                  358
                                  359
                                  360
                                  361
                                  362
                                  363
                                  364
                                  365
                                  366
                                  367
                                  368
                                  369
                                  370
                                  371
                                  372
                                  373
                                  374
                                  375
                                  376
                                  377
                                  378
                                  379
                                  380
                                  381
                                  382
                                  383
                                  384
                                  385
                                  386
                                  387
                                  388
                                  389
                                  390
                                  391
                                  392
                                  393
                                  394
                                  395
                                  396
                                  397
                                  398
                                  399
                                  400
                                  401
                                  402
                                  403
                                  404
                                  405
                                  406
                                  407
                                  408
                                  409
                                  410
                                  411
                                  412
                                  413
                                  414
                                  415
                                  416
                                  417
                                  418
                                  419
                                  420
                                  421
                                  422
                                  423
                                  424
                                  425
                                  426
                                  427
                                  428
                                  429
                                  430
                                  431
                                  432
                                  433
                                  434
                                  435
                                  436
                                  437
                                  438
                                  439
                                  440
                                  441
                                  442
                                  443
                                  444
                                  445
                                  446
                                  447
                                  448
                                  449
                                  450
                                  451
                                  452
                                  453
                                  454
                                  455
                                  456
                                  457
                                  458
                                  459
                                  460
                                  461
                                  462
                                  463
                                  464
                                  465
                                  466
                                  467
                                  468
                                  469
                                  470
                                  471
                                  472
                                  473
                                  474
                                  475
                                  476
                                  477
                                  478
                                  479
                                  480
                                  481
                                  482
                                  483
                                  484
                                  485
                                  486
                                  487
                                  488
                                  489
                                  490
                                  491
                                  492
                                  493
                                  494
                                  495
                                  496
                                  497
                                  498
                                  499
                                  500
                                  501
                                  502
                                  503
                                  504
                                  505
                                  506
                                  507
                                  508
                                  509
                                  510
                                  511
                                  512
                                  513
                                  514
                                  515
                                  516
                                  517
                                  518
                                  519
                                  520
                                  521
                                  522
                                  523
                                  524
                                  525
                                  526
                                  527
                                  528
                                  529
                                  530
                                  531
                                  532
                                  533
                                  534
                                  535
                                  536
                                  537
                                  538
                                  539
                                  540
                                  541
                                  542
                                  543
                                  544
                                  545
                                  546
                                  547
                                  548
                                  549
                                  550
                                  551
                                  552
                                  553
                                  554
                                  555
                                  556
                                  557
                                  558
                                  559
                                  560
                                  561
                                  562
                                  563
                                  564
                                  565
                                  566
                                  567
                                  568
                                  569
                                  570
                                  571
                                  572
                                  573
                                  574
                                  575
                                  576
                                  577
                                  578
                                  579
                                  580
                                  581
                                  582
                                  583
                                  584
                                  585
                                  586
                                  587
                                  588
                                  589
                                  590
                                  591
                                  @dataclass
                                  class ClaudeAgentOptions:
                                      """Query options for Claude SDK."""
                                  
                                      # Tools
                                      tools: list[ToolName | str] | ToolsPreset | None = None
                                      """Tools available to the agent."""
                                      allowed_tools: list[ToolName | str] | None = None
                                      """Tools which execute without prompting for permission."""
                                      disallowed_tools: list[ToolName | str] | None = None
                                      """Tools that are removed from agent context and cant be used."""
                                      enable_agent_teams: bool = False
                                      """Enable the experimental agent teams feature."""
                                      disable_parallel_tool_use: bool = False
                                      """Disable parallel too use (only one tool_use block per response)."""
                                      tool_config: ToolConfig | None = None
                                      """Per-tool configuration for built-in tools."""
                                      enable_tool_search: bool | int | Literal["auto"] | None = None
                                      """Enable or disable MCP tool search.
                                  
                                      When many MCP tools are configured, tool definitions can consume a
                                      significant portion of the context window. Tool search dynamically
                                      loads tools on-demand instead of preloading all of them.
                                  
                                      - ``True``: Always enabled.
                                      - ``False``: Always disabled, all MCP tools loaded upfront.
                                      - ``"auto"``: Activates when MCP tools exceed 10% of context (default behavior).
                                      - ``int``: Auto-activates at this percentage threshold (e.g. ``5`` for 5%).
                                      - ``None`` (default): Uses Claude Code's default (auto at 10%).
                                  
                                      Requires models that support ``tool_reference`` blocks (Sonnet 4+, Opus 4+).
                                      """
                                      fine_grained_tool_streaming: bool | Literal["auto"] = "auto"
                                      """Stream tool input to the client as the model writes it (fine-grained tool streaming).
                                  
                                      With it, ``stream_event`` messages carry tool input JSON as it is generated, so a UI can
                                      show a long ``Write``/``Edit`` input live and the tool call starts sooner. It saves no
                                      tokens. The partial tool input JSON is not validated by the API, and some endpoints
                                      reject the request with HTTP 400 (proxies / gateways, some models on Bedrock and Vertex).
                                  
                                      - ``"auto"`` (default): on when the CLI talks to Anthropic's API directly (no
                                        ``CLAUDE_CODE_USE_BEDROCK`` / ``_VERTEX`` / other provider env, ``ANTHROPIC_BASE_URL``
                                        unset or ``api.anthropic.com``); otherwise the CLI's own default applies.
                                      - ``True`` / ``False``: force it on / off.
                                  
                                      ``CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING`` in ``env`` overrides this option.
                                      """
                                      # MCP
                                      mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
                                      """MCP servers for the agent."""
                                      mcp_servers_delivery: Literal["argv", "initialize"] = "initialize"
                                      """How the ``mcp_servers`` that Claude Code runs or connects to (stdio, SSE, HTTP) reach it.
                                  
                                      - ``"initialize"`` (default): in the initialize request over stdin (the CLI is started
                                        with ``--await-initialize``), so server ``env`` and ``headers`` stay off the command
                                        line, where other users of the machine can read them. Needs Claude Code 2.1.261 or
                                        newer; connecting fails if the CLI does not take them (``mcp_servers_applied``).
                                      - ``"argv"``: in one ``--mcp-config`` flag, for older Claude Code. Deprecated upstream.
                                  
                                      In-process servers (``McpSdkServerConfigWithInstance``) and an ``mcp_servers`` file path
                                      are not affected, and a launch with ``--sdk-url`` in ``extra_args`` always uses
                                      ``--mcp-config``, as that session cannot read the request at launch.
                                      """
                                      chrome: bool = False
                                      """Add the chrome-tools MCP server (-> Claude Code browser extension) to the agent."""
                                      strict_mcp_config: bool = False
                                      """Enforce strict validation of MCP server configurations."""
                                      # Permissions
                                      permission_mode: PermissionMode | None = None
                                      """Permission mode."""
                                      allow_dangerously_skip_permissions: bool = False
                                      """Must be True when using permission_mode='bypassPermissions'."""
                                      on_permission: CanUseTool | str | None = None
                                      """Permission handler for tool execution.
                                  
                                      Accepts either:
                                      - A callback function (``CanUseTool``): The SDK routes permission requests
                                        through the control protocol to this callback. Automatically adds
                                        ``--permission-prompt-tool stdio`` to the CLI.
                                      - A string: Name of an MCP tool to handle permission prompts
                                        (passed as ``--permission-prompt-tool <name>`` to the CLI).
                                      - ``None``: Default behavior.
                                  
                                      Interaction with ``permission_mode``:
                                  
                                      - ``"default"``: All tool calls are routed to this handler.
                                      - ``"acceptEdits"``: All tool calls are routed to this handler.
                                        The handler is responsible for implementing the auto-approve-edits policy.
                                      - ``"plan"``: Only the synthetic ``ExitPlanMode`` tool is routed here.
                                        Actual modification tools are blocked by the CLI before reaching the handler.
                                      - ``"dontAsk"``: This handler is NEVER invoked. The CLI auto-denies all
                                        tools not pre-approved via the permissions config internally.
                                      - ``"bypassPermissions"``: This handler is NEVER invoked. The CLI
                                        auto-approves all tools internally.
                                  
                                      Tools that ``allowed_tools`` allows outright (``"Read"``, ``"Read()"``, ``"Read(*)"``)
                                      never reach the handler either. Connecting emits a ``CanUseToolShadowedWarning`` when
                                      a callback is set together with ``"bypassPermissions"`` or such entries.
                                      """
                                      on_user_question: OnUserQuestion | None = None
                                      """Callback for handling AskUserQuestion elicitation requests.
                                  
                                      Called when Claude asks the user a clarifying question via the
                                      AskUserQuestion tool. If not set, these requests fall through
                                      to on_permission (if it's a callback) for backwards compatibility.
                                      """
                                      permission_prompts: Literal["host", "none"] | None = None
                                      """Who answers permission prompts.
                                  
                                      ``"host"`` (default): this process, through ``on_permission``.
                                      ``"none"``: nobody - permission mode, rules and hooks still decide, and anything
                                      that would otherwise prompt is denied immediately.
                                      """
                                      on_elicitation: OnElicitation | None = None
                                      """Callback for handling MCP elicitation requests.
                                  
                                      Called when an MCP server requests user input (form fields, URL auth, etc.)
                                      and no hook handles the request first.
                                  
                                      If not provided, elicitation requests that aren't handled by hooks will
                                      be declined automatically.
                                      """
                                      # Session
                                      session: str | SessionConfig | None = None
                                      """Session configuration.
                                  
                                      Controls how the CLI session is started:
                                      - ``None`` or ``NewSession()``: Start a fresh session.
                                      - ``"session-id"`` or ``ResumeSession(session_id="...")``: Resume by ID.
                                      - ``ContinueLatest()``: Continue the most recent conversation.
                                      """
                                      # Limits
                                      max_turns: int | None = None
                                      """Maximum allowed amount of agentic turns."""
                                      max_budget_usd: float | None = None
                                      """Maximum amount of USD budget which may be consumed."""
                                      task_budget: int | None = None
                                      """API-side task budget in tokens.
                                  
                                      When set, the model is made aware of its remaining token budget so it can
                                      pace tool use and wrap up before the limit.  The CLI sends this as
                                      ``output_config.task_budget`` with the ``task-budgets-2026-03-13`` beta
                                      header automatically.
                                      """
                                      # Model
                                      model: ModelName | str | None = None
                                      """Session model."""
                                      fallback_model: ModelName | str | None = None
                                      """Fallback model in case default one is overloaded."""
                                      # Thinking
                                      thinking: ThinkingConfig | None = None
                                      """Controls thinking behavior."""
                                      effort: ReasoningEffort | None = None
                                      """Effort level for thinking depth."""
                                      # CLI SubProcess
                                      cli_path: str | Path | None = None
                                      """CLI path override (auto-detects by default)."""
                                      extra_args: dict[str, str | None] = field(default_factory=dict)
                                      """Arbitrary extra CLI flags."""
                                      max_buffer_size: int = 10 * 1024 * 1024
                                      """Max bytes when buffering CLI stdout."""
                                      stderr: Callable[[str], None] | None = None
                                      """Callback for stderr output from CLI."""
                                      env: dict[str, str] = field(default_factory=dict)
                                      """Environment variables for the CLI subprocess."""
                                      user: str | None = None
                                      """User for the AnyIO process."""
                                      # CWD
                                      add_dirs: Sequence[str | Path] = field(default_factory=list)
                                      """Add additional working directories."""
                                      cwd: str | Path | None = None
                                      """The working directory for the agent."""
                                      project_config_root: str | Path | None = None
                                      """The trusted checkout that ``cwd`` is a worktree of.
                                  
                                      Project settings, ``.mcp.json``, the ``.claude`` config trees and
                                      ``CLAUDE_PROJECT_DIR`` come from here instead of ``cwd``. Absolute path.
                                      """
                                      # Settings
                                      settings: str | Path | ClaudeCodeSettings | None = None
                                      """Settings configuration.
                                  
                                      Accepts:
                                      - A ``str`` or ``Path``: interpreted as a path to a settings JSON file.
                                      - A ``ClaudeCodeSettings`` instance: serialized to JSON automatically.
                                      - ``None``: no explicit settings.
                                      """
                                      setting_sources: list[SettingSource] | None = None
                                      """Sources to load filesystem settings from.
                                  
                                      None loads the CLI's defaults (user, project, local); ``[]`` loads none.
                                      """
                                      skills: list[str] | None = None
                                      """List of skills to use for the agent."""
                                      sandbox: Sandbox | None = None
                                      """Sandbox configuration for bash command isolation.
                                  
                                      Filesystem and network restrictions are derived from permission rules (Read/Edit/WebFetch),
                                      not from these sandbox settings.
                                      """
                                      debug_file: str | None = None
                                      """Write debug logs to a specific file path. Implicitly enables debug mode."""
                                      # Agent config
                                      system_prompt: str | list[str] | None = None
                                      """System prompt for the agent."""
                                      include_builtin_system_prompt: bool = True
                                      """Whether to include Claude Code's builtin system prompt.
                                  
                                  
                                      When True (default) and system_prompt is set, it is appended to the
                                      builtin system prompt. When False, the system_prompt replaces it entirely.
                                      """
                                      exclude_dynamic_sections: bool | None = None
                                      """Whether to exclude dynamic sections from the system prompt."""
                                      system_prompt_snapshot: bool | None = None
                                      """Snapshot the system prompt on the first request and reuse it verbatim.
                                  
                                      Keeps the prompt byte-identical across requests and resumes (better cache hits).
                                      """
                                      plan_mode_instructions: str | None = None
                                      """Custom workflow body for the plan-mode system reminder."""
                                  
                                      hooks: dict[HookEvent, list[HookMatcher]] | None = None
                                      """Hook configurations."""
                                      agents: dict[str, AgentDefinition] | None = None
                                      """SubAgent definitions."""
                                      plugins: list[SdkPluginConfig] = field(default_factory=list)
                                      """"Plugin configurations to load."""
                                      plugin_delivery: Literal["argv", "initialize"] = "argv"
                                      """How ``plugins`` reach Claude Code.
                                  
                                      - ``"argv"`` (default): one ``--plugin-dir`` flag per plugin. Works with any Claude Code
                                        version, but the command line grows with the plugin count (Windows refuses one past
                                        32,767 characters).
                                      - ``"initialize"``: in the initialize request over stdin (the CLI is started with
                                        ``--await-initialize``); connecting fails if the CLI does not load them
                                        (``plugins_applied``). A launch with ``--sdk-url`` in ``extra_args`` always uses argv.
                                      """
                                      capture_sdk_mcp_manifests: bool = True
                                      """Do the in-process MCP servers' handshake before connecting and send its results.
                                  
                                      The initialize request then carries each server's ``initialize`` and first
                                      ``tools/list`` results (``sdkMcpServerManifests``), so the CLI connects them without
                                      control round trips before the first turn. A server whose handshake fails, or that the
                                      CLI does not take, is handshaken over the control channel as before. Off when the
                                      ``CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS`` environment variable is set (as upstream).
                                      """
                                      output_schema: dict[str, Any] | type | None = None
                                      """JSON schema for structured output.
                                  
                                      Accepts either a JSON schema dict or a Python type (Pydantic model,
                                      dataclass, TypedDict, etc.) which will be converted to a JSON schema
                                      automatically.
                                  
                                      When set, Claude will return responses conforming to this schema.
                                  
                                      Examples:
                                          # As a dict
                                          output_schema={"type": "object", "properties": {"name": {"type": "string"}}}
                                          # As a type
                                          output_schema=MyPydanticModel
                                      """
                                      # Other
                                      enable_file_checkpointing: bool = False
                                      """Enable file checkpointing to track file changes during the session.
                                  
                                      When enabled, files can be rewound to their state at any user message
                                      using `ClaudeSDKClient.rewind_files()`.
                                      """
                                      agent: str | None = None
                                      """Agent name for the main thread. The agent must be defined in `agents` or settings."""
                                      context_1m: bool = False
                                      """Enable 1M token context window (Sonnet 4/4.5 only)."""
                                      prompt_suggestions: bool | None = None
                                      """Whether to create prompt suggestions."""
                                      agent_progress_summaries: bool | None = None
                                      """Enable periodic AI-generated progress summaries for running subagents.
                                  
                                      When True, the subagent's conversation is forked every ~30s to produce a short
                                      present-tense description (e.g. 'Analyzing authentication module'), emitted
                                      on task_progress events via the summary field. The fork reuses the
                                      subagent's model and prompt cache, so cost is typically minimal.
                                  
                                      Applies to both foreground and background subagents. Defaults to False.
                                      """
                                      include_hook_events: bool = False
                                      """Include hook lifecycle events in the output stream.
                                  
                                      When True, ``hook_started``, ``hook_progress``, and ``hook_response`` system
                                      messages will be emitted for all hook event types. SessionStart and Setup
                                      hook events are always emitted regardless of this setting.
                                      """
                                      replay_user_messages: bool | None = None
                                      """Whether to replay user messages in the session."""
                                      forward_subagent_text: bool = False
                                      """Forward subagent text and thinking blocks as messages with ``parent_tool_use_id`` set.
                                  
                                      By default only tool_use/tool_result blocks from subagents are emitted.
                                      """
                                      verbatim_prompts: bool = False
                                      """Send every user message with ``client_composed: true``.
                                  
                                      The CLI then delivers the prompt text as written: no ``@path`` expansion and
                                      no slash-command dispatch. Requires Claude Code 2.1.248+.
                                      """
                                      tool_aliases: dict[str, str] | None = None
                                      """Redirect built-in tool names to other tools, e.g. ``{"Bash": "mcp__ws__bash"}``.
                                  
                                      Single-hop; complementary to ``disallowed_tools``, not a replacement.
                                      """
                                      per_task_stop_affordance: bool | None = None
                                      """Declare that this consumer can stop individual background tasks (``stop_task``).
                                  
                                      When declared, an interrupt only aborts the current turn and spares running
                                      background agents/workflows.
                                      """
                                      worktree: bool | str = False
                                      """Create a new git worktree for the session (with optional name)."""
                                      instrument: bool = False
                                      """Whether to instrument the session with tracing hooks."""
                                  
                                      def build_settings_value(self) -> str | None:
                                          """Build the CLI ``--settings`` value, merging sandbox if provided.
                                  
                                          Returns:
                                              A JSON string, a file path, or None.
                                          """
                                          import anyenv
                                  
                                          from clawd_code_sdk.models.settings import ClaudeCodeSettings as _Settings
                                  
                                          # Resolve settings to a dict (or pass through as file path)
                                          match self.settings:
                                              case _Settings() as model:
                                                  settings_obj = model.model_dump(by_alias=True, exclude_none=True)
                                              case str() | Path() as value if self.sandbox:
                                                  settings_obj = self._load_settings_for_sandbox_merge(value)
                                              case str() | Path() as path:  # No sandbox to merge, pass file path directly to CLI
                                                  return str(path)
                                              case None:
                                                  settings_obj = {}
                                              case _ as unreachable:
                                                  assert_never(unreachable)
                                  
                                          # Merge sandbox settings
                                          if self.sandbox is not None:
                                              settings_obj["sandbox"] = self.sandbox.model_dump(by_alias=True, exclude_none=True)
                                  
                                          return anyenv.dump_json(settings_obj) if settings_obj else None
                                  
                                      def _load_settings_for_sandbox_merge(self, value: str | Path) -> dict[str, Any]:
                                          """Load ``settings`` (inline JSON or a file) so sandbox can be merged into it.
                                  
                                          Fails closed (upstream #1426): if the settings cannot be loaded, the CLI
                                          must not start with the sandbox settings alone, silently missing the
                                          caller's permission rules and hooks. A relative path is resolved against
                                          ``cwd``, as the CLI does when it reads the file itself.
                                  
                                          Raises:
                                              CLIConnectionError: If the settings are missing, unreadable, invalid
                                                  JSON, or not a JSON object.
                                          """
                                          from clawd_code_sdk._errors import CLIConnectionError
                                  
                                          if isinstance(value, str) and value.lstrip().startswith("{"):
                                              try:
                                                  loaded = json.loads(value)
                                              except json.JSONDecodeError as e:
                                                  # The inline value is not logged or echoed: it can hold secrets.
                                                  msg = f"Inline settings JSON is invalid (line {e.lineno}, column {e.colno})"
                                                  raise CLIConnectionError(msg) from None
                                              source = "Inline settings JSON"
                                          else:
                                              path = Path(value)
                                              if not path.is_absolute() and self.cwd is not None:
                                                  path = Path(self.cwd) / path
                                              try:
                                                  loaded = json.loads(path.read_text(encoding="utf-8"))
                                              except OSError as e:
                                                  msg = f"Cannot read settings file {path} to merge sandbox settings: {e}"
                                                  raise CLIConnectionError(msg) from e
                                              except json.JSONDecodeError as e:
                                                  msg = f"Settings file {path} is not valid JSON: {e}"
                                                  raise CLIConnectionError(msg) from e
                                              source = f"Settings file {path}"
                                          if not isinstance(loaded, dict):
                                              raise CLIConnectionError(f"{source} must contain a JSON object")
                                          return loaded
                                  
                                      def initialize_mcp_servers(self) -> dict[str, dict[str, Any]] | None:
                                          """The servers to send in the initialize request, or None to send none there."""
                                          if self.mcp_servers_delivery != "initialize" or "sdk-url" in self.extra_args:
                                              return None
                                          if not isinstance(self.mcp_servers, dict):
                                              return None
                                          servers = {
                                              name: _serialize_mcp_server(config)
                                              for name, config in self.mcp_servers.items()
                                              if config.type != "sdk"
                                          }
                                          return servers or None
                                  
                                      def initialize_plugins(self) -> list[dict[str, Any]] | None:
                                          """The plugins to send in the initialize request, or None to pass them as flags."""
                                          if self.plugin_delivery != "initialize" or "sdk-url" in self.extra_args:
                                              return None
                                          plugins = [p.model_dump(by_alias=True, exclude_none=True) for p in self.plugins]
                                          return plugins or None
                                  
                                      def reads_initialize_at_launch(self) -> bool:
                                          """Whether the CLI waits for the initialize request (``--await-initialize``)."""
                                          return self.initialize_mcp_servers() is not None or self.initialize_plugins() is not None
                                  
                                      def sdk_mcp_server_configs(self) -> dict[str, dict[str, Any]] | None:
                                          """Settings of the in-process MCP servers (timeout, tool policy), by server name."""
                                          from clawd_code_sdk.models.mcp import McpSdkServerConfig
                                  
                                          if not isinstance(self.mcp_servers, dict):
                                              return None
                                          configs: dict[str, dict[str, Any]] = {}
                                          for name, config in self.mcp_servers.items():
                                              if not isinstance(config, McpSdkServerConfig):
                                                  continue
                                              settings: dict[str, Any] = {}
                                              if config.timeout is not None:
                                                  settings["timeout"] = config.timeout
                                              if config.tools is not None:
                                                  settings["tools"] = [
                                                      {k: v for k, v in dataclasses.asdict(t).items() if v is not None}
                                                      for t in config.tools
                                                  ]
                                              if settings:
                                                  configs[name] = settings
                                          return configs or None
                                  
                                      def argv_mcp_servers(self) -> dict[str, dict[str, Any]]:
                                          """The servers for ``--mcp-config``.
                                  
                                          All of them, or only the in-process ones when the others go in the initialize request.
                                          """
                                          if not isinstance(self.mcp_servers, dict):
                                              return {}
                                          in_initialize = self.initialize_mcp_servers() is not None
                                          return {
                                              name: _serialize_mcp_server(config)
                                              for name, config in self.mcp_servers.items()
                                              if not in_initialize or config.type == "sdk"
                                          }
                                  
                                      def get_json_schema(self) -> dict[str, Any] | None:
                                          from pydantic import TypeAdapter
                                  
                                          match self.output_schema:
                                              case type() as typ:
                                                  return TypeAdapter(typ).json_schema()
                                              case dict() as schema:
                                                  return schema
                                              case None:
                                                  return None
                                              case _ as unreachable:
                                                  assert_never(unreachable)
                                  
                                      def get_session(self) -> SessionConfig:
                                          match self.session:
                                              case None:
                                                  return NewSession()
                                              case str() as session_id:
                                                  return ResumeSession(session_id=session_id)
                                              case NewSession() | ResumeSession() | ContinueLatest() | FromPR() as config:
                                                  return config
                                              case _ as unreachable:
                                                  assert_never(unreachable)
                                  

                                  add_dirs class-attribute instance-attribute

                                  add_dirs: Sequence[str | Path] = field(default_factory=list)
                                  

                                  Add additional working directories.

                                  agent class-attribute instance-attribute

                                  agent: str | None = None
                                  

                                  Agent name for the main thread. The agent must be defined in agents or settings.

                                  agent_progress_summaries class-attribute instance-attribute

                                  agent_progress_summaries: bool | None = None
                                  

                                  Enable periodic AI-generated progress summaries for running subagents.

                                  When True, the subagent's conversation is forked every ~30s to produce a short present-tense description (e.g. 'Analyzing authentication module'), emitted on task_progress events via the summary field. The fork reuses the subagent's model and prompt cache, so cost is typically minimal.

                                  Applies to both foreground and background subagents. Defaults to False.

                                  agents class-attribute instance-attribute

                                  agents: dict[str, AgentDefinition] | None = None
                                  

                                  SubAgent definitions.

                                  allow_dangerously_skip_permissions class-attribute instance-attribute

                                  allow_dangerously_skip_permissions: bool = False
                                  

                                  Must be True when using permission_mode='bypassPermissions'.

                                  allowed_tools class-attribute instance-attribute

                                  allowed_tools: list[ToolName | str] | None = None
                                  

                                  Tools which execute without prompting for permission.

                                  capture_sdk_mcp_manifests class-attribute instance-attribute

                                  capture_sdk_mcp_manifests: bool = True
                                  

                                  Do the in-process MCP servers' handshake before connecting and send its results.

                                  The initialize request then carries each server's initialize and first tools/list results (sdkMcpServerManifests), so the CLI connects them without control round trips before the first turn. A server whose handshake fails, or that the CLI does not take, is handshaken over the control channel as before. Off when the CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS environment variable is set (as upstream).

                                  chrome class-attribute instance-attribute

                                  chrome: bool = False
                                  

                                  Add the chrome-tools MCP server (-> Claude Code browser extension) to the agent.

                                  cli_path class-attribute instance-attribute

                                  cli_path: str | Path | None = None
                                  

                                  CLI path override (auto-detects by default).

                                  context_1m class-attribute instance-attribute

                                  context_1m: bool = False
                                  

                                  Enable 1M token context window (Sonnet 4/4.5 only).

                                  cwd class-attribute instance-attribute

                                  cwd: str | Path | None = None
                                  

                                  The working directory for the agent.

                                  debug_file class-attribute instance-attribute

                                  debug_file: str | None = None
                                  

                                  Write debug logs to a specific file path. Implicitly enables debug mode.

                                  disable_parallel_tool_use class-attribute instance-attribute

                                  disable_parallel_tool_use: bool = False
                                  

                                  Disable parallel too use (only one tool_use block per response).

                                  disallowed_tools class-attribute instance-attribute

                                  disallowed_tools: list[ToolName | str] | None = None
                                  

                                  Tools that are removed from agent context and cant be used.

                                  effort class-attribute instance-attribute

                                  effort: ReasoningEffort | None = None
                                  

                                  Effort level for thinking depth.

                                  enable_agent_teams class-attribute instance-attribute

                                  enable_agent_teams: bool = False
                                  

                                  Enable the experimental agent teams feature.

                                  enable_file_checkpointing class-attribute instance-attribute

                                  enable_file_checkpointing: bool = False
                                  

                                  Enable file checkpointing to track file changes during the session.

                                  When enabled, files can be rewound to their state at any user message using ClaudeSDKClient.rewind_files().

                                  enable_tool_search: bool | int | Literal['auto'] | None = None
                                  

                                  Enable or disable MCP tool search.

                                  When many MCP tools are configured, tool definitions can consume a significant portion of the context window. Tool search dynamically loads tools on-demand instead of preloading all of them.

                                  • True: Always enabled.
                                  • False: Always disabled, all MCP tools loaded upfront.
                                  • "auto": Activates when MCP tools exceed 10% of context (default behavior).
                                  • int: Auto-activates at this percentage threshold (e.g. 5 for 5%).
                                  • None (default): Uses Claude Code's default (auto at 10%).

                                  Requires models that support tool_reference blocks (Sonnet 4+, Opus 4+).

                                  env class-attribute instance-attribute

                                  env: dict[str, str] = field(default_factory=dict)
                                  

                                  Environment variables for the CLI subprocess.

                                  exclude_dynamic_sections class-attribute instance-attribute

                                  exclude_dynamic_sections: bool | None = None
                                  

                                  Whether to exclude dynamic sections from the system prompt.

                                  extra_args class-attribute instance-attribute

                                  extra_args: dict[str, str | None] = field(default_factory=dict)
                                  

                                  Arbitrary extra CLI flags.

                                  fallback_model class-attribute instance-attribute

                                  fallback_model: ModelName | str | None = None
                                  

                                  Fallback model in case default one is overloaded.

                                  fine_grained_tool_streaming class-attribute instance-attribute

                                  fine_grained_tool_streaming: bool | Literal['auto'] = 'auto'
                                  

                                  Stream tool input to the client as the model writes it (fine-grained tool streaming).

                                  With it, stream_event messages carry tool input JSON as it is generated, so a UI can show a long Write/Edit input live and the tool call starts sooner. It saves no tokens. The partial tool input JSON is not validated by the API, and some endpoints reject the request with HTTP 400 (proxies / gateways, some models on Bedrock and Vertex).

                                  • "auto" (default): on when the CLI talks to Anthropic's API directly (no CLAUDE_CODE_USE_BEDROCK / _VERTEX / other provider env, ANTHROPIC_BASE_URL unset or api.anthropic.com); otherwise the CLI's own default applies.
                                  • True / False: force it on / off.

                                  CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING in env overrides this option.

                                  forward_subagent_text class-attribute instance-attribute

                                  forward_subagent_text: bool = False
                                  

                                  Forward subagent text and thinking blocks as messages with parent_tool_use_id set.

                                  By default only tool_use/tool_result blocks from subagents are emitted.

                                  hooks class-attribute instance-attribute

                                  hooks: dict[HookEvent, list[HookMatcher]] | None = None
                                  

                                  Hook configurations.

                                  include_builtin_system_prompt class-attribute instance-attribute

                                  include_builtin_system_prompt: bool = True
                                  

                                  Whether to include Claude Code's builtin system prompt.

                                  When True (default) and system_prompt is set, it is appended to the builtin system prompt. When False, the system_prompt replaces it entirely.

                                  include_hook_events class-attribute instance-attribute

                                  include_hook_events: bool = False
                                  

                                  Include hook lifecycle events in the output stream.

                                  When True, hook_started, hook_progress, and hook_response system messages will be emitted for all hook event types. SessionStart and Setup hook events are always emitted regardless of this setting.

                                  instrument class-attribute instance-attribute

                                  instrument: bool = False
                                  

                                  Whether to instrument the session with tracing hooks.

                                  max_budget_usd class-attribute instance-attribute

                                  max_budget_usd: float | None = None
                                  

                                  Maximum amount of USD budget which may be consumed.

                                  max_buffer_size class-attribute instance-attribute

                                  max_buffer_size: int = 10 * 1024 * 1024
                                  

                                  Max bytes when buffering CLI stdout.

                                  max_turns class-attribute instance-attribute

                                  max_turns: int | None = None
                                  

                                  Maximum allowed amount of agentic turns.

                                  mcp_servers class-attribute instance-attribute

                                  mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
                                  

                                  MCP servers for the agent.

                                  mcp_servers_delivery class-attribute instance-attribute

                                  mcp_servers_delivery: Literal['argv', 'initialize'] = 'initialize'
                                  

                                  How the mcp_servers that Claude Code runs or connects to (stdio, SSE, HTTP) reach it.

                                  • "initialize" (default): in the initialize request over stdin (the CLI is started with --await-initialize), so server env and headers stay off the command line, where other users of the machine can read them. Needs Claude Code 2.1.261 or newer; connecting fails if the CLI does not take them (mcp_servers_applied).
                                  • "argv": in one --mcp-config flag, for older Claude Code. Deprecated upstream.

                                  In-process servers (McpSdkServerConfigWithInstance) and an mcp_servers file path are not affected, and a launch with --sdk-url in extra_args always uses --mcp-config, as that session cannot read the request at launch.

                                  model class-attribute instance-attribute

                                  model: ModelName | str | None = None
                                  

                                  Session model.

                                  on_elicitation class-attribute instance-attribute

                                  on_elicitation: OnElicitation | None = None
                                  

                                  Callback for handling MCP elicitation requests.

                                  Called when an MCP server requests user input (form fields, URL auth, etc.) and no hook handles the request first.

                                  If not provided, elicitation requests that aren't handled by hooks will be declined automatically.

                                  on_permission class-attribute instance-attribute

                                  on_permission: CanUseTool | str | None = None
                                  

                                  Permission handler for tool execution.

                                  Accepts either: - A callback function (CanUseTool): The SDK routes permission requests through the control protocol to this callback. Automatically adds --permission-prompt-tool stdio to the CLI. - A string: Name of an MCP tool to handle permission prompts (passed as --permission-prompt-tool <name> to the CLI). - None: Default behavior.

                                  Interaction with permission_mode:

                                  • "default": All tool calls are routed to this handler.
                                  • "acceptEdits": All tool calls are routed to this handler. The handler is responsible for implementing the auto-approve-edits policy.
                                  • "plan": Only the synthetic ExitPlanMode tool is routed here. Actual modification tools are blocked by the CLI before reaching the handler.
                                  • "dontAsk": This handler is NEVER invoked. The CLI auto-denies all tools not pre-approved via the permissions config internally.
                                  • "bypassPermissions": This handler is NEVER invoked. The CLI auto-approves all tools internally.

                                  Tools that allowed_tools allows outright ("Read", "Read()", "Read(*)") never reach the handler either. Connecting emits a CanUseToolShadowedWarning when a callback is set together with "bypassPermissions" or such entries.

                                  on_user_question class-attribute instance-attribute

                                  on_user_question: OnUserQuestion | None = None
                                  

                                  Callback for handling AskUserQuestion elicitation requests.

                                  Called when Claude asks the user a clarifying question via the AskUserQuestion tool. If not set, these requests fall through to on_permission (if it's a callback) for backwards compatibility.

                                  output_schema class-attribute instance-attribute

                                  output_schema: dict[str, Any] | type | None = None
                                  

                                  JSON schema for structured output.

                                  Accepts either a JSON schema dict or a Python type (Pydantic model, dataclass, TypedDict, etc.) which will be converted to a JSON schema automatically.

                                  When set, Claude will return responses conforming to this schema.

                                  Examples:

                                  As a dict

                                  output_schema={"type": "object", "properties": {"name": {"type": "string"}}}

                                  As a type

                                  output_schema=MyPydanticModel

                                  per_task_stop_affordance class-attribute instance-attribute

                                  per_task_stop_affordance: bool | None = None
                                  

                                  Declare that this consumer can stop individual background tasks (stop_task).

                                  When declared, an interrupt only aborts the current turn and spares running background agents/workflows.

                                  permission_mode class-attribute instance-attribute

                                  permission_mode: PermissionMode | None = None
                                  

                                  Permission mode.

                                  permission_prompts class-attribute instance-attribute

                                  permission_prompts: Literal['host', 'none'] | None = None
                                  

                                  Who answers permission prompts.

                                  "host" (default): this process, through on_permission. "none": nobody - permission mode, rules and hooks still decide, and anything that would otherwise prompt is denied immediately.

                                  plan_mode_instructions class-attribute instance-attribute

                                  plan_mode_instructions: str | None = None
                                  

                                  Custom workflow body for the plan-mode system reminder.

                                  plugin_delivery class-attribute instance-attribute

                                  plugin_delivery: Literal['argv', 'initialize'] = 'argv'
                                  

                                  How plugins reach Claude Code.

                                  • "argv" (default): one --plugin-dir flag per plugin. Works with any Claude Code version, but the command line grows with the plugin count (Windows refuses one past 32,767 characters).
                                  • "initialize": in the initialize request over stdin (the CLI is started with --await-initialize); connecting fails if the CLI does not load them (plugins_applied). A launch with --sdk-url in extra_args always uses argv.

                                  plugins class-attribute instance-attribute

                                  plugins: list[SdkPluginConfig] = field(default_factory=list)
                                  

                                  "Plugin configurations to load.

                                  project_config_root class-attribute instance-attribute

                                  project_config_root: str | Path | None = None
                                  

                                  The trusted checkout that cwd is a worktree of.

                                  Project settings, .mcp.json, the .claude config trees and CLAUDE_PROJECT_DIR come from here instead of cwd. Absolute path.

                                  prompt_suggestions class-attribute instance-attribute

                                  prompt_suggestions: bool | None = None
                                  

                                  Whether to create prompt suggestions.

                                  replay_user_messages class-attribute instance-attribute

                                  replay_user_messages: bool | None = None
                                  

                                  Whether to replay user messages in the session.

                                  sandbox class-attribute instance-attribute

                                  sandbox: Sandbox | None = None
                                  

                                  Sandbox configuration for bash command isolation.

                                  Filesystem and network restrictions are derived from permission rules (Read/Edit/WebFetch), not from these sandbox settings.

                                  session class-attribute instance-attribute

                                  session: str | SessionConfig | None = None
                                  

                                  Session configuration.

                                  Controls how the CLI session is started: - None or NewSession(): Start a fresh session. - "session-id" or ResumeSession(session_id="..."): Resume by ID. - ContinueLatest(): Continue the most recent conversation.

                                  setting_sources class-attribute instance-attribute

                                  setting_sources: list[SettingSource] | None = None
                                  

                                  Sources to load filesystem settings from.

                                  None loads the CLI's defaults (user, project, local); [] loads none.

                                  settings class-attribute instance-attribute

                                  settings: str | Path | ClaudeCodeSettings | None = None
                                  

                                  Settings configuration.

                                  Accepts: - A str or Path: interpreted as a path to a settings JSON file. - A ClaudeCodeSettings instance: serialized to JSON automatically. - None: no explicit settings.

                                  skills class-attribute instance-attribute

                                  skills: list[str] | None = None
                                  

                                  List of skills to use for the agent.

                                  stderr class-attribute instance-attribute

                                  stderr: Callable[[str], None] | None = None
                                  

                                  Callback for stderr output from CLI.

                                  strict_mcp_config class-attribute instance-attribute

                                  strict_mcp_config: bool = False
                                  

                                  Enforce strict validation of MCP server configurations.

                                  system_prompt class-attribute instance-attribute

                                  system_prompt: str | list[str] | None = None
                                  

                                  System prompt for the agent.

                                  system_prompt_snapshot class-attribute instance-attribute

                                  system_prompt_snapshot: bool | None = None
                                  

                                  Snapshot the system prompt on the first request and reuse it verbatim.

                                  Keeps the prompt byte-identical across requests and resumes (better cache hits).

                                  task_budget class-attribute instance-attribute

                                  task_budget: int | None = None
                                  

                                  API-side task budget in tokens.

                                  When set, the model is made aware of its remaining token budget so it can pace tool use and wrap up before the limit. The CLI sends this as output_config.task_budget with the task-budgets-2026-03-13 beta header automatically.

                                  thinking class-attribute instance-attribute

                                  thinking: ThinkingConfig | None = None
                                  

                                  Controls thinking behavior.

                                  tool_aliases class-attribute instance-attribute

                                  tool_aliases: dict[str, str] | None = None
                                  

                                  Redirect built-in tool names to other tools, e.g. {"Bash": "mcp__ws__bash"}.

                                  Single-hop; complementary to disallowed_tools, not a replacement.

                                  tool_config class-attribute instance-attribute

                                  tool_config: ToolConfig | None = None
                                  

                                  Per-tool configuration for built-in tools.

                                  tools class-attribute instance-attribute

                                  tools: list[ToolName | str] | ToolsPreset | None = None
                                  

                                  Tools available to the agent.

                                  user class-attribute instance-attribute

                                  user: str | None = None
                                  

                                  User for the AnyIO process.

                                  verbatim_prompts class-attribute instance-attribute

                                  verbatim_prompts: bool = False
                                  

                                  Send every user message with client_composed: true.

                                  The CLI then delivers the prompt text as written: no @path expansion and no slash-command dispatch. Requires Claude Code 2.1.248+.

                                  worktree class-attribute instance-attribute

                                  worktree: bool | str = False
                                  

                                  Create a new git worktree for the session (with optional name).

                                  argv_mcp_servers

                                  argv_mcp_servers() -> dict[str, dict[str, Any]]
                                  

                                  The servers for --mcp-config.

                                  All of them, or only the in-process ones when the others go in the initialize request.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  def argv_mcp_servers(self) -> dict[str, dict[str, Any]]:
                                      """The servers for ``--mcp-config``.
                                  
                                      All of them, or only the in-process ones when the others go in the initialize request.
                                      """
                                      if not isinstance(self.mcp_servers, dict):
                                          return {}
                                      in_initialize = self.initialize_mcp_servers() is not None
                                      return {
                                          name: _serialize_mcp_server(config)
                                          for name, config in self.mcp_servers.items()
                                          if not in_initialize or config.type == "sdk"
                                      }
                                  

                                  build_settings_value

                                  build_settings_value() -> str | None
                                  

                                  Build the CLI --settings value, merging sandbox if provided.

                                  Returns:

                                  Type Description
                                  str | None

                                  A JSON string, a file path, or None.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  def build_settings_value(self) -> str | None:
                                      """Build the CLI ``--settings`` value, merging sandbox if provided.
                                  
                                      Returns:
                                          A JSON string, a file path, or None.
                                      """
                                      import anyenv
                                  
                                      from clawd_code_sdk.models.settings import ClaudeCodeSettings as _Settings
                                  
                                      # Resolve settings to a dict (or pass through as file path)
                                      match self.settings:
                                          case _Settings() as model:
                                              settings_obj = model.model_dump(by_alias=True, exclude_none=True)
                                          case str() | Path() as value if self.sandbox:
                                              settings_obj = self._load_settings_for_sandbox_merge(value)
                                          case str() | Path() as path:  # No sandbox to merge, pass file path directly to CLI
                                              return str(path)
                                          case None:
                                              settings_obj = {}
                                          case _ as unreachable:
                                              assert_never(unreachable)
                                  
                                      # Merge sandbox settings
                                      if self.sandbox is not None:
                                          settings_obj["sandbox"] = self.sandbox.model_dump(by_alias=True, exclude_none=True)
                                  
                                      return anyenv.dump_json(settings_obj) if settings_obj else None
                                  

                                  initialize_mcp_servers

                                  initialize_mcp_servers() -> dict[str, dict[str, Any]] | None
                                  

                                  The servers to send in the initialize request, or None to send none there.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  def initialize_mcp_servers(self) -> dict[str, dict[str, Any]] | None:
                                      """The servers to send in the initialize request, or None to send none there."""
                                      if self.mcp_servers_delivery != "initialize" or "sdk-url" in self.extra_args:
                                          return None
                                      if not isinstance(self.mcp_servers, dict):
                                          return None
                                      servers = {
                                          name: _serialize_mcp_server(config)
                                          for name, config in self.mcp_servers.items()
                                          if config.type != "sdk"
                                      }
                                      return servers or None
                                  

                                  initialize_plugins

                                  initialize_plugins() -> list[dict[str, Any]] | None
                                  

                                  The plugins to send in the initialize request, or None to pass them as flags.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  def initialize_plugins(self) -> list[dict[str, Any]] | None:
                                      """The plugins to send in the initialize request, or None to pass them as flags."""
                                      if self.plugin_delivery != "initialize" or "sdk-url" in self.extra_args:
                                          return None
                                      plugins = [p.model_dump(by_alias=True, exclude_none=True) for p in self.plugins]
                                      return plugins or None
                                  

                                  reads_initialize_at_launch

                                  reads_initialize_at_launch() -> bool
                                  

                                  Whether the CLI waits for the initialize request (--await-initialize).

                                  Source code in src/clawd_code_sdk/models/options.py
                                  def reads_initialize_at_launch(self) -> bool:
                                      """Whether the CLI waits for the initialize request (``--await-initialize``)."""
                                      return self.initialize_mcp_servers() is not None or self.initialize_plugins() is not None
                                  

                                  sdk_mcp_server_configs

                                  sdk_mcp_server_configs() -> dict[str, dict[str, Any]] | None
                                  

                                  Settings of the in-process MCP servers (timeout, tool policy), by server name.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  def sdk_mcp_server_configs(self) -> dict[str, dict[str, Any]] | None:
                                      """Settings of the in-process MCP servers (timeout, tool policy), by server name."""
                                      from clawd_code_sdk.models.mcp import McpSdkServerConfig
                                  
                                      if not isinstance(self.mcp_servers, dict):
                                          return None
                                      configs: dict[str, dict[str, Any]] = {}
                                      for name, config in self.mcp_servers.items():
                                          if not isinstance(config, McpSdkServerConfig):
                                              continue
                                          settings: dict[str, Any] = {}
                                          if config.timeout is not None:
                                              settings["timeout"] = config.timeout
                                          if config.tools is not None:
                                              settings["tools"] = [
                                                  {k: v for k, v in dataclasses.asdict(t).items() if v is not None}
                                                  for t in config.tools
                                              ]
                                          if settings:
                                              configs[name] = settings
                                      return configs or None
                                  

                                  ClaudeCodeSettings

                                  Bases: ClaudeCodeBaseModel

                                  Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings.

                                  Source code in src/clawd_code_sdk/models/settings.py
                                  3505
                                  3506
                                  3507
                                  3508
                                  3509
                                  3510
                                  3511
                                  3512
                                  3513
                                  3514
                                  3515
                                  3516
                                  3517
                                  3518
                                  3519
                                  3520
                                  3521
                                  3522
                                  3523
                                  3524
                                  3525
                                  3526
                                  3527
                                  3528
                                  3529
                                  3530
                                  3531
                                  3532
                                  3533
                                  3534
                                  3535
                                  3536
                                  3537
                                  3538
                                  3539
                                  3540
                                  3541
                                  3542
                                  3543
                                  3544
                                  3545
                                  3546
                                  3547
                                  3548
                                  3549
                                  3550
                                  3551
                                  3552
                                  3553
                                  3554
                                  3555
                                  3556
                                  3557
                                  3558
                                  3559
                                  3560
                                  3561
                                  3562
                                  3563
                                  3564
                                  3565
                                  3566
                                  3567
                                  3568
                                  3569
                                  3570
                                  3571
                                  3572
                                  3573
                                  3574
                                  3575
                                  3576
                                  3577
                                  3578
                                  3579
                                  3580
                                  3581
                                  3582
                                  3583
                                  3584
                                  3585
                                  3586
                                  3587
                                  3588
                                  3589
                                  3590
                                  3591
                                  3592
                                  3593
                                  3594
                                  3595
                                  3596
                                  3597
                                  3598
                                  3599
                                  3600
                                  3601
                                  3602
                                  3603
                                  3604
                                  3605
                                  3606
                                  3607
                                  3608
                                  3609
                                  3610
                                  3611
                                  3612
                                  3613
                                  3614
                                  3615
                                  3616
                                  3617
                                  3618
                                  3619
                                  3620
                                  3621
                                  3622
                                  3623
                                  3624
                                  3625
                                  3626
                                  3627
                                  3628
                                  3629
                                  3630
                                  3631
                                  3632
                                  3633
                                  3634
                                  3635
                                  3636
                                  3637
                                  3638
                                  3639
                                  3640
                                  3641
                                  3642
                                  3643
                                  3644
                                  3645
                                  3646
                                  3647
                                  3648
                                  3649
                                  3650
                                  3651
                                  3652
                                  3653
                                  3654
                                  3655
                                  3656
                                  3657
                                  3658
                                  3659
                                  3660
                                  3661
                                  3662
                                  3663
                                  3664
                                  3665
                                  3666
                                  3667
                                  3668
                                  3669
                                  3670
                                  3671
                                  3672
                                  3673
                                  3674
                                  3675
                                  3676
                                  3677
                                  3678
                                  3679
                                  3680
                                  3681
                                  3682
                                  3683
                                  3684
                                  3685
                                  3686
                                  3687
                                  3688
                                  3689
                                  3690
                                  3691
                                  3692
                                  3693
                                  3694
                                  3695
                                  3696
                                  3697
                                  3698
                                  3699
                                  3700
                                  3701
                                  3702
                                  3703
                                  3704
                                  3705
                                  3706
                                  3707
                                  3708
                                  3709
                                  3710
                                  3711
                                  3712
                                  3713
                                  3714
                                  3715
                                  3716
                                  3717
                                  3718
                                  3719
                                  3720
                                  3721
                                  3722
                                  3723
                                  3724
                                  3725
                                  3726
                                  3727
                                  3728
                                  3729
                                  3730
                                  3731
                                  3732
                                  3733
                                  3734
                                  3735
                                  3736
                                  3737
                                  3738
                                  3739
                                  3740
                                  3741
                                  3742
                                  3743
                                  3744
                                  3745
                                  3746
                                  3747
                                  3748
                                  3749
                                  3750
                                  3751
                                  3752
                                  3753
                                  3754
                                  3755
                                  3756
                                  3757
                                  3758
                                  3759
                                  3760
                                  3761
                                  3762
                                  3763
                                  3764
                                  3765
                                  3766
                                  3767
                                  3768
                                  3769
                                  3770
                                  3771
                                  3772
                                  3773
                                  3774
                                  3775
                                  3776
                                  3777
                                  3778
                                  3779
                                  3780
                                  3781
                                  3782
                                  3783
                                  3784
                                  3785
                                  3786
                                  3787
                                  3788
                                  3789
                                  3790
                                  3791
                                  3792
                                  3793
                                  3794
                                  3795
                                  3796
                                  3797
                                  3798
                                  3799
                                  3800
                                  3801
                                  3802
                                  3803
                                  3804
                                  3805
                                  3806
                                  3807
                                  3808
                                  3809
                                  3810
                                  3811
                                  3812
                                  3813
                                  3814
                                  3815
                                  3816
                                  3817
                                  3818
                                  3819
                                  3820
                                  3821
                                  3822
                                  3823
                                  3824
                                  3825
                                  3826
                                  3827
                                  3828
                                  3829
                                  3830
                                  3831
                                  3832
                                  3833
                                  3834
                                  3835
                                  3836
                                  3837
                                  3838
                                  3839
                                  3840
                                  3841
                                  3842
                                  3843
                                  3844
                                  3845
                                  3846
                                  3847
                                  3848
                                  3849
                                  3850
                                  3851
                                  3852
                                  3853
                                  3854
                                  3855
                                  3856
                                  3857
                                  3858
                                  3859
                                  3860
                                  3861
                                  3862
                                  3863
                                  3864
                                  3865
                                  3866
                                  3867
                                  3868
                                  3869
                                  3870
                                  3871
                                  3872
                                  3873
                                  3874
                                  3875
                                  3876
                                  3877
                                  3878
                                  3879
                                  3880
                                  3881
                                  3882
                                  3883
                                  3884
                                  3885
                                  3886
                                  3887
                                  3888
                                  3889
                                  3890
                                  3891
                                  3892
                                  3893
                                  3894
                                  3895
                                  3896
                                  3897
                                  3898
                                  3899
                                  3900
                                  3901
                                  3902
                                  3903
                                  3904
                                  3905
                                  3906
                                  3907
                                  3908
                                  3909
                                  3910
                                  3911
                                  3912
                                  3913
                                  3914
                                  3915
                                  3916
                                  3917
                                  3918
                                  3919
                                  3920
                                  3921
                                  3922
                                  3923
                                  3924
                                  3925
                                  3926
                                  3927
                                  3928
                                  3929
                                  3930
                                  3931
                                  3932
                                  3933
                                  3934
                                  3935
                                  3936
                                  3937
                                  3938
                                  3939
                                  3940
                                  3941
                                  3942
                                  3943
                                  3944
                                  3945
                                  3946
                                  3947
                                  3948
                                  3949
                                  3950
                                  3951
                                  3952
                                  3953
                                  3954
                                  3955
                                  3956
                                  3957
                                  3958
                                  3959
                                  3960
                                  3961
                                  3962
                                  3963
                                  3964
                                  3965
                                  3966
                                  3967
                                  3968
                                  3969
                                  3970
                                  3971
                                  3972
                                  3973
                                  3974
                                  3975
                                  3976
                                  3977
                                  3978
                                  3979
                                  3980
                                  3981
                                  3982
                                  3983
                                  3984
                                  3985
                                  3986
                                  3987
                                  3988
                                  3989
                                  3990
                                  3991
                                  3992
                                  3993
                                  3994
                                  3995
                                  3996
                                  3997
                                  3998
                                  3999
                                  4000
                                  4001
                                  4002
                                  4003
                                  4004
                                  4005
                                  4006
                                  4007
                                  4008
                                  4009
                                  4010
                                  4011
                                  4012
                                  4013
                                  4014
                                  4015
                                  4016
                                  4017
                                  4018
                                  4019
                                  4020
                                  4021
                                  4022
                                  4023
                                  4024
                                  4025
                                  4026
                                  4027
                                  4028
                                  4029
                                  4030
                                  4031
                                  4032
                                  4033
                                  4034
                                  4035
                                  4036
                                  4037
                                  4038
                                  4039
                                  4040
                                  4041
                                  4042
                                  4043
                                  4044
                                  4045
                                  4046
                                  4047
                                  4048
                                  4049
                                  4050
                                  4051
                                  4052
                                  4053
                                  4054
                                  4055
                                  4056
                                  4057
                                  4058
                                  4059
                                  4060
                                  4061
                                  4062
                                  4063
                                  4064
                                  4065
                                  4066
                                  4067
                                  4068
                                  4069
                                  4070
                                  4071
                                  4072
                                  4073
                                  4074
                                  4075
                                  4076
                                  4077
                                  4078
                                  4079
                                  4080
                                  4081
                                  4082
                                  4083
                                  4084
                                  4085
                                  4086
                                  4087
                                  4088
                                  4089
                                  4090
                                  4091
                                  4092
                                  4093
                                  4094
                                  4095
                                  4096
                                  4097
                                  4098
                                  4099
                                  4100
                                  4101
                                  4102
                                  4103
                                  4104
                                  4105
                                  4106
                                  4107
                                  4108
                                  4109
                                  4110
                                  4111
                                  4112
                                  4113
                                  4114
                                  4115
                                  4116
                                  4117
                                  4118
                                  4119
                                  4120
                                  4121
                                  4122
                                  4123
                                  4124
                                  4125
                                  4126
                                  4127
                                  4128
                                  4129
                                  4130
                                  4131
                                  4132
                                  4133
                                  4134
                                  4135
                                  4136
                                  4137
                                  4138
                                  4139
                                  4140
                                  4141
                                  4142
                                  4143
                                  4144
                                  4145
                                  4146
                                  4147
                                  4148
                                  4149
                                  4150
                                  4151
                                  4152
                                  4153
                                  4154
                                  4155
                                  4156
                                  4157
                                  4158
                                  4159
                                  4160
                                  4161
                                  4162
                                  4163
                                  4164
                                  4165
                                  4166
                                  4167
                                  4168
                                  4169
                                  4170
                                  4171
                                  4172
                                  4173
                                  4174
                                  4175
                                  4176
                                  4177
                                  4178
                                  4179
                                  4180
                                  4181
                                  4182
                                  4183
                                  4184
                                  4185
                                  4186
                                  4187
                                  4188
                                  4189
                                  4190
                                  4191
                                  4192
                                  4193
                                  4194
                                  4195
                                  4196
                                  4197
                                  4198
                                  4199
                                  4200
                                  4201
                                  4202
                                  4203
                                  4204
                                  4205
                                  4206
                                  4207
                                  4208
                                  4209
                                  4210
                                  4211
                                  4212
                                  4213
                                  4214
                                  4215
                                  4216
                                  4217
                                  4218
                                  4219
                                  4220
                                  4221
                                  4222
                                  4223
                                  4224
                                  4225
                                  4226
                                  4227
                                  4228
                                  4229
                                  4230
                                  4231
                                  4232
                                  4233
                                  4234
                                  4235
                                  4236
                                  4237
                                  4238
                                  4239
                                  4240
                                  4241
                                  4242
                                  4243
                                  4244
                                  4245
                                  4246
                                  4247
                                  4248
                                  4249
                                  4250
                                  4251
                                  4252
                                  4253
                                  4254
                                  4255
                                  4256
                                  4257
                                  4258
                                  4259
                                  4260
                                  4261
                                  4262
                                  4263
                                  4264
                                  4265
                                  4266
                                  4267
                                  4268
                                  4269
                                  4270
                                  4271
                                  4272
                                  4273
                                  4274
                                  4275
                                  4276
                                  4277
                                  4278
                                  4279
                                  4280
                                  4281
                                  4282
                                  4283
                                  4284
                                  4285
                                  4286
                                  4287
                                  4288
                                  4289
                                  4290
                                  4291
                                  4292
                                  4293
                                  4294
                                  4295
                                  4296
                                  4297
                                  4298
                                  4299
                                  4300
                                  4301
                                  4302
                                  class ClaudeCodeSettings(ClaudeCodeBaseModel):
                                      """Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings."""
                                  
                                      model_config = ConfigDict(
                                          extra="allow",
                                      )
                                      field_schema: str | None = Field(None, alias="$schema")
                                      """
                                      JSON Schema reference for Claude Code settings
                                      """
                                      api_key_helper: str | None = Field(
                                          None, alias="apiKeyHelper", examples=["/bin/generate_temp_api_key.sh"], min_length=1
                                      )
                                      """
                                      Path to a script that outputs authentication values. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      auto_memory_enabled: bool | None = Field(True, alias="autoMemoryEnabled")
                                      """
                                      Enable automatic memory saves that capture useful context to `~/.claude/projects/<project>/memory/` (derived from the git repository, shared across worktrees). Also configurable via CLAUDE_CODE_DISABLE_AUTO_MEMORY environment variable (set to 1 to disable, 0 to enable). See https://code.claude.com/docs/en/memory#storage-location
                                      """
                                      auto_updates_channel: Literal["stable", "latest"] | None = Field(
                                          "latest", alias="autoUpdatesChannel"
                                      )
                                      """
                                      Release channel to follow for updates. Use "stable" for a version that is typically about one week old and skips versions with major regressions, or "latest" (default) for the most recent release. Set DISABLE_AUTOUPDATER=1 to disable background auto-updates, or DISABLE_UPDATES=1 (added in v2.1.118) to block all update paths including manual `claude update`.
                                      """
                                      aws_credential_export: str | None = Field(
                                          None, alias="awsCredentialExport", examples=["/bin/generate_aws_grant.sh"], min_length=1
                                      )
                                      """
                                      Command that outputs AWS credentials as JSON (in the form {"Credentials": {"AccessKeyId": ..., "SecretAccessKey": ..., "SessionToken": ...}}). The output is captured silently. Use when you cannot modify the .aws directory and must return credentials directly. See https://code.claude.com/docs/en/amazon-bedrock#advanced-credential-configuration
                                      """
                                      aws_auth_refresh: str | None = Field(
                                          None, alias="awsAuthRefresh", examples=["aws sso login --profile myprofile"], min_length=1
                                      )
                                      """
                                      Command to run when AWS credentials are expired or unavailable; its output is shown to the user but interactive input is not supported. Also drives the "Claude Platform on AWS · refresh credentials" option in /login when configured. See https://code.claude.com/docs/en/amazon-bedrock#advanced-credential-configuration
                                      """
                                      claude_md_excludes: list[ClaudeMdExclude] | None = Field(
                                          None,
                                          alias="claudeMdExcludes",
                                          examples=[["**/monorepo/CLAUDE.md", "/home/user/monorepo/other-team/.claude/rules/**"]],
                                      )
                                      """
                                      Glob patterns for CLAUDE.md files to exclude from loading. Useful in monorepos to skip irrelevant instructions from other teams. Patterns match against absolute file paths. Arrays merge across settings layers. Managed policy CLAUDE.md files cannot be excluded. See https://code.claude.com/docs/en/memory#exclude-specific-claude-md-files
                                      """
                                      cleanup_period_days: int | None = Field(
                                          30, alias="cleanupPeriodDays", examples=[20, 30, 60], ge=1
                                      )
                                      """
                                      Number of days to retain sessions, orphaned subagent worktrees, tasks, shell snapshots, and backups. Minimum is 1; setting 0 is rejected with a validation error. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      env: Env | None = Field(
                                          default_factory=lambda: Env.model_validate({}),
                                          examples=[
                                              {
                                                  "ANTHROPIC_MODEL": "claude-opus-4-1",
                                                  "ANTHROPIC_SMALL_FAST_MODEL": "claude-3-5-haiku-latest",
                                              }
                                          ],
                                      )
                                      """
                                      Environment variables to set for Claude Code sessions. Many environment variables provide settings dimensions not available as dedicated settings.json properties (e.g., thinking tokens, prompt caching, bash timeouts, shell configuration). See https://code.claude.com/docs/en/settings#environment-variables for the full list.
                                      """
                                      attribution: Attribution | None = None
                                      """
                                      Customize attribution for git commits and pull requests. See https://code.claude.com/docs/en/settings#attribution-settings
                                      """
                                      include_git_instructions: bool | None = Field(True, alias="includeGitInstructions")
                                      """
                                      Include built-in git commit and PR workflow instructions in Claude's system prompt. Also configurable via CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS environment variable (set to 1 to disable). See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      include_co_authored_by: bool | None = Field(True, alias="includeCoAuthoredBy")
                                      """
                                      DEPRECATED. Use 'attribution' instead. Whether to include the co-authored-by Claude byline in git commits and pull requests (default: true)
                                      """
                                      plans_directory: str | None = Field(
                                          "~/.claude/plans", alias="plansDirectory", examples=["./plans"]
                                      )
                                      """
                                      Customize where plan files are stored. Path is relative to project root (default: ~/.claude/plans)
                                      """
                                      respect_gitignore: bool | None = Field(True, alias="respectGitignore")
                                      """
                                      Control whether the @ file picker respects .gitignore patterns. When true (default), files matching .gitignore patterns are excluded from suggestions
                                      """
                                      permissions: Permissions | None = Field(
                                          None,
                                          examples=[
                                              {
                                                  "allow": ["Bash(git add:*)"],
                                                  "ask": ["Bash(gh pr create:*)", "Bash(git commit:*)"],
                                                  "deny": ["Read(*.env)", "Bash(rm:*)", "Bash(curl:*)"],
                                                  "defaultMode": "default",
                                              }
                                          ],
                                      )
                                      """
                                      Tool usage permissions configuration.
                                      See https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings
                                      See https://code.claude.com/docs/en/tools-reference for full list of tools available to Claude.
                                      """
                                      language: str | None = Field(None, examples=["japanese", "spanish", "french"])
                                      """
                                      Configure Claude's preferred response language (e.g., "japanese", "spanish", "french"). Claude will respond in this language by default. Also sets the voice dictation language and terminal tab session title generation. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      model: str | None = None
                                      """
                                      Override the default model used by Claude Code. For finer control, use environment variables: ANTHROPIC_MODEL (runtime override), ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL (per-class pinning), CLAUDE_CODE_SUBAGENT_MODEL (subagent model). See https://code.claude.com/docs/en/model-config
                                      """
                                      available_models: list[str] | None = Field(
                                          None, alias="availableModels", examples=[["sonnet", "haiku"]]
                                      )
                                      """
                                      Restrict which models users can select. When defined at multiple settings levels (user, project, etc.), arrays are merged and deduplicated. See https://code.claude.com/docs/en/model-config#restrict-model-selection
                                      """
                                      model_overrides: dict[str, str] | None = Field(
                                          None,
                                          alias="modelOverrides",
                                          examples=[
                                              {
                                                  "claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod"
                                              }
                                          ],
                                      )
                                      """
                                      Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs, Vertex AI version names, or Foundry deployment names. Each model picker entry uses its mapped value when calling the provider API. Unknown keys are ignored. See https://code.claude.com/docs/en/model-config#override-model-ids-per-version
                                      """
                                      effort_level: Literal["low", "medium", "high", "xhigh", "max"] | None = Field(
                                          None, alias="effortLevel"
                                      )
                                      """
                                      Persist adaptive reasoning effort across sessions. Set to low, medium, high, or xhigh; max and ultracode are session-only and are not accepted in the settings file (use the CLAUDE_CODE_EFFORT_LEVEL environment variable or /effort for a session-only max). Effort is supported on Fable 5, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6, with xhigh sitting between high and max (added in v2.1.111). Defaults: Fable 5 and Opus 4.8 default to high; Opus 4.6 and Sonnet 4.6 default to high on all plans (Pro/Max raised from medium to high in v2.1.117); Opus 4.7 defaults to xhigh. Use /effort auto to reset to model default. Also configurable via CLAUDE_CODE_EFFORT_LEVEL environment variable. See https://code.claude.com/docs/en/model-config#adjust-effort-level
                                      """
                                      fast_mode: bool | None = Field(False, alias="fastMode")
                                      """
                                      Enable fast mode, which uses Claude Opus 5 by default (since v2.1.219) for faster output at higher per-token cost without downgrading to a smaller model. Requires extra usage enabled. Toggle with the /fast command. Supported on Opus 5 and Opus 4.8; fast mode for Opus 4.7 was deprecated on June 25, 2026 and removed on July 24, 2026. Before v2.1.219 fast mode defaulted to Opus 4.8 (v2.1.154 through v2.1.218) and to Opus 4.7 (v2.1.142 through v2.1.153). See https://code.claude.com/docs/en/fast-mode
                                      """
                                      fast_mode_per_session_opt_in: bool | None = Field(False, alias="fastModePerSessionOptIn")
                                      """
                                      Require per-session opt-in for fast mode. When true, fast mode does not persist across sessions and users must enable it with /fast each session. Useful for controlling costs. See https://code.claude.com/docs/en/fast-mode
                                      """
                                      feedback_survey_rate: float | None = Field(
                                          None, alias="feedbackSurveyRate", examples=[0.05], ge=0.0, le=1.0
                                      )
                                      """
                                      Probability (0–1) that the session quality survey appears when eligible. A value of 0.05 means 5% of eligible sessions. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      enable_all_project_mcp_servers: bool | None = Field(
                                          None, alias="enableAllProjectMcpServers", examples=[True]
                                      )
                                      """
                                      Whether to automatically approve all MCP servers in the project. See https://code.claude.com/docs/en/mcp
                                      """
                                      enabled_mcpjson_servers: list[EnabledMcpjsonServer] | None = Field(
                                          None, alias="enabledMcpjsonServers", examples=[["memory", "github"]]
                                      )
                                      """
                                      List of approved MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp
                                      """
                                      disabled_mcpjson_servers: list[DisabledMcpjsonServer] | None = Field(
                                          None, alias="disabledMcpjsonServers", examples=[["filesystem"]]
                                      )
                                      """
                                      List of rejected MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp
                                      """
                                      allowed_mcp_servers: (
                                          list[
                                              AllowedMcpServerByServerName
                                              | AllowedMcpServerByServerCommand
                                              | AllowedMcpServerByServerUrl
                                          ]
                                          | None
                                      ) = Field(None, alias="allowedMcpServers")
                                      """
                                      Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options
                                      """
                                      denied_mcp_servers: (
                                          list[
                                              DeniedMcpServerByServerName
                                              | DeniedMcpServerByServerCommand
                                              | DeniedMcpServerByServerUrl
                                          ]
                                          | None
                                      ) = Field(None, alias="deniedMcpServers")
                                      """
                                      Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options
                                      """
                                      http_hook_allowed_env_vars: list[HttpHookAllowedEnvVar] | None = Field(
                                          None, alias="httpHookAllowedEnvVars", examples=[["MY_TOKEN", "HOOK_SECRET"]]
                                      )
                                      """
                                      Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration
                                      """
                                      hooks: Hooks | None = Field(
                                          None,
                                          examples=[
                                              {
                                                  "PostToolUse": [
                                                      {
                                                          "matcher": "Edit|Write",
                                                          "hooks": [{"type": "command", "command": "prettier --write", "timeout": 5}],
                                                      }
                                                  ]
                                              }
                                          ],
                                      )
                                      """
                                      Lifecycle event hooks that run at configurable points during Claude Code operation (tool use, session start/end, notifications, prompt submit, message display, and more), not just before/after tool executions. See https://code.claude.com/docs/en/hooks
                                      """
                                      disable_all_hooks: bool | None = Field(None, alias="disableAllHooks")
                                      """
                                      Disable all hooks and statusLine execution. When true in managed settings, user and project-level disableAllHooks cannot override it. See https://code.claude.com/docs/en/hooks#disable-or-remove-hooks
                                      """
                                      allowed_channel_plugins: list[AllowedChannelPlugin] | None = Field(
                                          None, alias="allowedChannelPlugins"
                                      )
                                      """
                                      (Managed settings only) Allowlist of channel plugins that may run, each identified by its marketplace and plugin name. When set, only the listed plugins can push inbound channel messages while channelsEnabled is true. Replaces the default Anthropic allowlist when set; undefined falls back to the default and an empty array blocks all channel plugins. Requires channelsEnabled: true. See https://code.claude.com/docs/en/channels#restrict-which-channel-plugins-can-run
                                      """
                                      allowed_http_hook_urls: list[AllowedHttpHookUrl] | None = Field(
                                          None,
                                          alias="allowedHttpHookUrls",
                                          examples=[["https://hooks.example.com/*", "http://localhost:*"]],
                                      )
                                      """
                                      Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration
                                      """
                                      allow_managed_hooks_only: bool | None = Field(None, alias="allowManagedHooksOnly")
                                      """
                                      (Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See https://code.claude.com/docs/en/settings#hook-configuration
                                      """
                                      allow_managed_permission_rules_only: bool | None = Field(
                                          None, alias="allowManagedPermissionRulesOnly"
                                      )
                                      """
                                      (Managed settings only) Prevent user and project settings from defining allow, ask, or deny permission rules. Only rules in managed settings apply. See https://code.claude.com/docs/en/settings#permission-settings
                                      """
                                      status_line: StatusLine | None = Field(
                                          None,
                                          alias="statusLine",
                                          examples=[{"type": "command", "command": "~/.claude/statusline.sh"}],
                                      )
                                      """
                                      Custom status line display configuration. See https://code.claude.com/docs/en/statusline
                                      """
                                      file_suggestion: FileSuggestion | None = Field(
                                          None,
                                          alias="fileSuggestion",
                                          examples=[{"type": "command", "command": "~/.claude/file-suggestion.sh"}],
                                      )
                                      """
                                      Configure a custom script for @ file autocomplete. See https://code.claude.com/docs/en/settings#file-suggestion-settings
                                      """
                                      enabled_plugins: dict[str, list[str] | bool | Any] | None = Field(None, alias="enabledPlugins")
                                      """
                                      Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. See https://code.claude.com/docs/en/plugins
                                      """
                                      extra_known_marketplaces: dict[str, ExtraKnownMarketplaces] | None = Field(
                                          None, alias="extraKnownMarketplaces"
                                      )
                                      """
                                      Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources. See https://code.claude.com/docs/en/plugin-marketplaces
                                      """
                                      strict_known_marketplaces: (
                                          list[
                                              StrictMarketplaceHostPattern
                                              | StrictMarketplaceGithub
                                              | StrictMarketplaceGit
                                              | StrictMarketplaceUrl
                                              | StrictMarketplaceNpm
                                              | StrictMarketplaceFile
                                              | StrictMarketplaceDirectory
                                              | StrictMarketplacePathPattern
                                              | StrictMarketplaceSkillsDir
                                          ]
                                          | None
                                      ) = Field(
                                          None,
                                          alias="strictKnownMarketplaces",
                                          examples=[
                                              [
                                                  {"source": "github", "repo": "acme-corp/approved-plugins"},
                                                  {"source": "npm", "package": "@acme-corp/compliance-plugins"},
                                              ]
                                          ],
                                      )
                                      """
                                      (Managed settings only) Allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Uses exact matching for source specifications. See https://code.claude.com/docs/en/plugin-marketplaces#managed-marketplace-restrictions
                                      """
                                      skipped_marketplaces: list[SkippedMarketplace] | None = Field(None, alias="skippedMarketplaces")
                                      """
                                      List of marketplace names the user has chosen not to install when prompted. See https://code.claude.com/docs/en/discover-plugins
                                      """
                                      skipped_plugins: list[SkippedPlugin] | None = Field(None, alias="skippedPlugins")
                                      """
                                      List of plugin IDs (plugin@marketplace format) the user has chosen not to install when prompted. See https://code.claude.com/docs/en/discover-plugins
                                      """
                                      force_login_method: Literal["claudeai", "console", "gateway"] | None = Field(
                                          None, alias="forceLoginMethod", examples=["claudeai"]
                                      )
                                      """
                                      Use "claudeai" to restrict login to Claude.ai accounts, "console" to restrict login to Claude Console accounts, or "gateway" to restrict login to a cloud gateway. On Claude Code v2.1.212 or later, every first-party login path enforces the restriction, including the VS Code extension, the Agent SDK, `claude setup-token`, and /install-github-app; before v2.1.212, only terminal logins enforced it. See https://code.claude.com/docs/en/authentication#restrict-login-to-your-organization
                                      """
                                      force_login_org_uuid: ForceLoginOrgUuid | list[ForceLoginOrgUuidItem] | None = Field(
                                          None, alias="forceLoginOrgUUID", examples=["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"]
                                      )
                                      """
                                      Organization UUID to use for OAuth login, or an array of UUIDs to allow several organizations. An empty array fails closed and blocks every login. See https://code.claude.com/docs/en/authentication#restrict-login-to-your-organization
                                      """
                                      otel_headers_helper: str | None = Field(None, alias="otelHeadersHelper", min_length=1)
                                      """
                                      Path to an executable, or a shell command line with arguments, that outputs OpenTelemetry headers as a JSON object. Runs at startup and re-runs on the interval set by CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS. Requires CLAUDE_CODE_ENABLE_TELEMETRY=1. See https://code.claude.com/docs/en/monitoring-usage#dynamic-headers
                                      """
                                      output_style: str | None = Field(
                                          None,
                                          alias="outputStyle",
                                          examples=["default", "Proactive", "Explanatory", "Learning"],
                                          min_length=1,
                                      )
                                      """
                                      Controls the output style for assistant responses. Built-in styles: default, Proactive, Explanatory, Learning. Custom styles can be added in ~/.claude/output-styles/ or .claude/output-styles/. See https://code.claude.com/docs/en/output-styles
                                      """
                                      skip_web_fetch_preflight: bool | None = Field(None, alias="skipWebFetchPreflight")
                                      """
                                      Skip the WebFetch blocklist check for enterprise environments with restrictive security policies. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      sandbox: Sandbox | None = None
                                      """
                                      Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing
                                      """
                                      spinner_verbs: SpinnerVerbs | None = Field(None, alias="spinnerVerbs")
                                      """
                                      Customize the verbs shown in spinner progress messages
                                      """
                                      spinner_tips_enabled: bool | None = Field(True, alias="spinnerTipsEnabled")
                                      """
                                      Show tips in the spinner while Claude is working. Set to false to disable tips (default: true)
                                      """
                                      spinner_tips_override: SpinnerTipsOverride | None = Field(None, alias="spinnerTipsOverride")
                                      """
                                      Customize the tips displayed in the spinner while Claude is working. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      terminal_progress_bar_enabled: bool | None = Field(True, alias="terminalProgressBarEnabled")
                                      """
                                      Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: true)
                                      """
                                      show_turn_duration: bool | None = Field(True, alias="showTurnDuration")
                                      """
                                      Show turn duration messages after responses (e.g., "Cooked for 1m 6s"). Set to false to hide these messages (default: true)
                                      """
                                      skill_overrides: dict[str, Literal["on", "name-only", "user-invocable-only", "off"]] | None = (
                                          Field(
                                              None,
                                              alias="skillOverrides",
                                              examples=[{"legacy-context": "name-only", "deploy": "off"}],
                                          )
                                      )
                                      """
                                      Per-skill visibility overrides. Controls whether skills appear to Claude and in the / picker. Values: 'on' (name and description shown, default), 'name-only' (name only), 'user-invocable-only' (hidden from Claude, visible in /), 'off' (hidden everywhere). Plugin skills are not affected by this setting. See https://code.claude.com/docs/en/skills#override-skill-visibility-from-settings
                                      """
                                      prefers_reduced_motion: bool | None = Field(False, alias="prefersReducedMotion")
                                      """
                                      Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility
                                      """
                                      pr_url_template: str | None = Field(
                                          None,
                                          alias="prUrlTemplate",
                                          examples=["https://reviews.example.com/{owner}/{repo}/pull/{number}"],
                                      )
                                      """
                                      URL template for the PR badge shown in the footer and in tool-result summaries. Substitutes placeholders {host}, {owner}, {repo}, {number}, {url} from the gh-reported PR URL. Use this to point PR links at an internal code-review tool instead of github.com. Does not affect #123 autolinks in Claude's prose. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      always_thinking_enabled: bool | None = Field(None, alias="alwaysThinkingEnabled")
                                      """
                                      Enable extended thinking by default for all sessions. Typically configured via the /config command rather than editing directly. See https://code.claude.com/docs/en/common-workflows#use-extended-thinking-thinking-mode
                                      """
                                      company_announcements: list[CompanyAnnouncement] | None = Field(
                                          None, alias="companyAnnouncements"
                                      )
                                      """
                                      Company announcements to display at startup (one will be randomly selected if multiple are provided)
                                      """
                                      teammate_mode: Literal["auto", "in-process", "tmux", "iterm2"] | None = Field(
                                          "in-process", alias="teammateMode"
                                      )
                                      """
                                      How agent team teammates display: "auto" picks split panes in tmux or iTerm2, in-process otherwise; "iterm2" (added in v2.1.186) forces iTerm2 native split panes and requires the it2 CLI (it shows an error with the install command if it2 is missing). The default is "in-process" (it was "auto" before v2.1.179). Agent teams are experimental and disabled by default. Enable them by adding CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to your settings.json or environment. See https://code.claude.com/docs/en/agent-teams#choose-a-display-mode
                                      """
                                      worktree: Worktree | None = None
                                      """
                                      Configuration for --worktree sessions. See https://code.claude.com/docs/en/settings#worktree-settings
                                      """
                                      parent_settings_behavior: Literal["first-wins", "merge"] | None = Field(
                                          "first-wins", alias="parentSettingsBehavior"
                                      )
                                      """
                                      (Admin/managed settings only) Controls how SDK managedSettings (parent tier) merge with inherited settings. 'first-wins': first non-empty value applies (default). 'merge': merge arrays and objects. See https://code.claude.com/docs/en/server-managed-settings
                                      """
                                      plugin_trust_message: str | None = Field(None, alias="pluginTrustMessage", min_length=1)
                                      """
                                      (Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use to provide organization-specific context about approved plugins. See https://code.claude.com/docs/en/settings#plugin-settings
                                      """
                                      plugin_configs: dict[str, PluginConfigs] | None = Field(None, alias="pluginConfigs")
                                      """
                                      Per-plugin configuration including MCP server user configs and plugin options, keyed by plugin ID (plugin@marketplace format). See https://code.claude.com/docs/en/plugins
                                      """
                                      allow_managed_mcp_servers_only: bool | None = Field(None, alias="allowManagedMcpServersOnly")
                                      """
                                      (Managed settings only) When true, only allowedMcpServers from managed settings are respected; MCP servers defined in user, project, or local settings are ignored. deniedMcpServers still merges from all sources. See https://code.claude.com/docs/en/managed-mcp
                                      """
                                      blocked_marketplaces: (
                                          list[
                                              BlockedMarketplaceUrl
                                              | BlockedMarketplaceGithub
                                              | BlockedMarketplaceGit
                                              | BlockedMarketplaceNpm
                                              | BlockedMarketplaceFile
                                              | BlockedMarketplaceDirectory
                                              | BlockedMarketplaceHostPattern
                                              | BlockedMarketplacePathPattern
                                              | BlockedMarketplaceSkillsDir
                                          ]
                                          | None
                                      ) = Field(None, alias="blockedMarketplaces")
                                      """
                                      (Managed settings only) Blocklist of marketplace sources. These exact sources are blocked from being added as marketplaces. The check happens before downloading, so blocked sources never touch the filesystem.
                                      """
                                      agent: str | None = Field(None, min_length=1)
                                      """
                                      Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model. See https://code.claude.com/docs/en/sub-agents
                                      """
                                      auto_memory_directory: str | None = Field(None, alias="autoMemoryDirectory", min_length=1)
                                      """
                                      Custom directory path for auto-memory storage. Supports ~/ prefix for home-directory expansion. Ignored if set in checked-in project settings (.claude/settings.json) for security. Defaults to `~/.claude/projects/<sanitized-cwd>/memory/` when unset. See https://code.claude.com/docs/en/memory
                                      """
                                      auto_mode: AutoMode | None = Field(None, alias="autoMode")
                                      """
                                      Customization for the auto mode classifier prompt. Typically configured in managed settings to tune the allow/deny rules used when permissions.defaultMode is "auto". By default, allow, soft_deny, and environment REPLACE the corresponding built-in classifier section entirely. Include the literal string "$defaults" as an array entry (added in v2.1.118) to splice the built-in defaults in at that position alongside your custom rules. See https://code.claude.com/docs/en/permissions
                                      """
                                      channels_enabled: bool | None = Field(None, alias="channelsEnabled")
                                      """
                                      (Managed settings only) Allow channels for the organization. On claude.ai Team and Enterprise plans, channels are blocked when this is unset or false. For Anthropic Console accounts using API key authentication, channels are allowed by default unless the organization deploys managed settings, in which case this key must be set to true. See https://code.claude.com/docs/en/channels#enterprise-controls
                                      """
                                      default_shell: Literal["bash", "powershell"] | None = Field(None, alias="defaultShell")
                                      """
                                      Default shell for input-box ! commands. Default: bash. Using "powershell" routes ! commands through PowerShell on Windows and requires CLAUDE_CODE_USE_POWERSHELL_TOOL=1 with pwsh on PATH. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      disable_deep_link_registration: Literal["disable"] | None = Field(
                                          None, alias="disableDeepLinkRegistration"
                                      )
                                      """
                                      Set to "disable" to prevent Claude Code from registering the `claude-cli://` deep-link protocol handler on startup. Most useful in managed settings where users cannot override it. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      disable_skill_shell_execution: bool | None = Field(None, alias="disableSkillShellExecution")
                                      """
                                      Disable inline shell execution for `` !`...` `` and ` ```! ` blocks in skills and custom slash commands from user, project, plugin, or additional-directory sources. Commands are replaced with [shell command execution disabled by policy] instead of being run. Bundled and managed skills are not affected. Most useful in managed settings where users cannot override it. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      force_remote_settings_refresh: bool | None = Field(None, alias="forceRemoteSettingsRefresh")
                                      """
                                      (Managed settings only) Block CLI startup until remote managed settings are freshly fetched from the server. If the fetch fails, the CLI exits (fail-closed) rather than continuing with cached settings. When not set, startup continues without waiting for remote settings. See https://code.claude.com/docs/en/server-managed-settings
                                      """
                                      minimum_version: str | None = Field(
                                          None, alias="minimumVersion", examples=["2.1.0"], min_length=1
                                      )
                                      """
                                      Minimum Claude Code version to stay on. Prevents downgrades when switching release channels. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      show_clear_context_on_plan_accept: bool | None = Field(
                                          False, alias="showClearContextOnPlanAccept"
                                      )
                                      """
                                      When true, the plan-approval dialog offers a "clear context" option. Defaults to false.
                                      """
                                      show_thinking_summaries: bool | None = Field(False, alias="showThinkingSummaries")
                                      """
                                      Show thinking summaries in the transcript view (Ctrl+O). Thinking summaries are not generated by default in interactive sessions; set to true to restore. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      skip_dangerous_mode_permission_prompt: bool | None = Field(
                                          None, alias="skipDangerousModePermissionPrompt"
                                      )
                                      """
                                      Whether the user has accepted the bypass permissions mode dialog. Typically managed by the CLI rather than set by hand.
                                      """
                                      strict_plugin_only_customization: bool | StrictPluginOnlyCustomization | None = Field(
                                          None, alias="strictPluginOnlyCustomization"
                                      )
                                      """
                                      (Managed settings) Block non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g., ["skills", "hooks"]); true locks all four; false is an explicit no-op. See https://code.claude.com/docs/en/plugins-reference
                                      """
                                      tui: Literal["fullscreen", "default"] | None = None
                                      """
                                      TUI rendering mode. Use "fullscreen" for the flicker-free alt-screen renderer with virtualized scrollback; "default" for the classic main-screen renderer. Corresponds to the /tui command. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      view_mode: Literal["default", "verbose", "focus"] | None = Field(None, alias="viewMode")
                                      """
                                      Transcript view mode. "default" shows standard interactive view; "verbose" shows expanded tool details; "focus" shows prompt, one-line tool summaries, and final response only (Ctrl+O toggle). See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      use_auto_mode_during_plan: bool | None = Field(None, alias="useAutoModeDuringPlan")
                                      """
                                      When true, apply the auto mode classifier during plan mode to auto-approve safe read-only tool calls while planning. Has no effect unless permissions.defaultMode allows auto. See https://code.claude.com/docs/en/permissions
                                      """
                                      voice_enabled: bool | None = Field(None, alias="voiceEnabled")
                                      """
                                      Legacy alias for voice.enabled; prefer the voice object. Requires a Claude.ai account. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      wsl_inherits_windows_settings: bool | None = Field(None, alias="wslInheritsWindowsSettings")
                                      """
                                      (Windows managed settings only) When true, Claude Code on WSL reads managed settings from the Windows policy chain in addition to /etc/claude-code, with Windows sources taking priority. Only honored when set in the HKLM registry key or C:\\Program Files\\ClaudeCode\\managed-settings.json, both of which require Windows admin to write. For HKCU policy to also apply on WSL, the flag must additionally be set in HKCU itself. Has no effect on native Windows. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      subagent_status_line: SubagentStatusLine | None = Field(None, alias="subagentStatusLine")
                                      """
                                      Status line configuration for subagent sessions. See https://code.claude.com/docs/en/statusline#subagent-status-lines
                                      """
                                      advisor_model: str | None = Field(None, alias="advisorModel")
                                      """
                                      Model for the server-side advisor tool. Accepts a model alias ("opus", "sonnet", or "fable" on v2.1.170+) or a full model ID. Overridden by the --advisor CLI flag for the session, and blocked when the model is outside the availableModels allowlist. See https://code.claude.com/docs/en/advisor
                                      """
                                      auto_compact_enabled: bool | None = Field(True, alias="autoCompactEnabled")
                                      """
                                      Automatically compact the conversation when context approaches the limit. Also configurable via the DISABLE_AUTO_COMPACT environment variable. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      disable_agent_view: bool | None = Field(None, alias="disableAgentView")
                                      """
                                      (Managed settings) Turn off background agents and the agent view: claude agents, --bg, /background, and the on-demand supervisor. Also configurable via the CLAUDE_CODE_DISABLE_AGENT_VIEW environment variable (set to 1 to disable). See https://code.claude.com/docs/en/agent-view
                                      """
                                      editor_mode: Literal["normal", "vim"] | None = Field("normal", alias="editorMode")
                                      """
                                      Key binding mode for the input prompt: "normal" or "vim". Appears in /config as Editor mode. See https://code.claude.com/docs/en/terminal-config#edit-prompts-with-vim-keybindings
                                      """
                                      enforce_available_models: bool | None = Field(None, alias="enforceAvailableModels")
                                      """
                                      (Managed settings) Extend the availableModels allowlist to the Default model option (requires v2.1.175+). Requires a non-empty availableModels list; when the account-type default is not in the allowlist, Default resolves to the first allowed entry instead. Has no effect when availableModels is unset or empty. See https://code.claude.com/docs/en/model-config#enforce-the-allowlist-for-the-default-model
                                      """
                                      fallback_model: list[str] | None = Field(None, alias="fallbackModel", max_length=3)
                                      """
                                      Fallback model chain tried in order when the primary model is overloaded, unavailable, or returns a non-retryable server error. Capped at three entries after deduplication; accepts model names or aliases, and "default" expands to the account-type default. Overridden by the --fallback-model CLI flag for the session. See https://code.claude.com/docs/en/model-config#fallback-model-chains
                                      """
                                      file_checkpointing_enabled: bool | None = Field(True, alias="fileCheckpointingEnabled")
                                      """
                                      Snapshot edited files so /rewind can restore them. Also configurable via the CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING environment variable (set to 1 to disable). See https://code.claude.com/docs/en/checkpointing
                                      """
                                      gcp_auth_refresh: str | None = Field(
                                          None,
                                          alias="gcpAuthRefresh",
                                          examples=["gcloud auth application-default login"],
                                          min_length=1,
                                      )
                                      """
                                      Command to run when GCP credentials are expired or cannot be loaded. The command's output is displayed to the user but interactive input is not supported; it times out after three minutes. See https://code.claude.com/docs/en/google-vertex-ai#advanced-credential-configuration
                                      """
                                      managed_mcp_servers: list[dict[str, Any]] | None = Field(None, alias="managedMcpServers")
                                      """
                                      (Managed settings, third-party Desktop deployments only) MCP server configurations pushed to all users. Each entry specifies the transport and connection details, plus an optional toolPolicy map. Delivered through the managed settings file or MDM. See https://code.claude.com/docs/en/desktop#enterprise-configuration
                                      """
                                      skill_listing_max_desc_chars: int | None = Field(1536, alias="skillListingMaxDescChars", gt=0)
                                      """
                                      Per-skill character cap on the combined description and when_to_use text in the skill listing Claude sees each turn. Text longer than this is truncated. See https://code.claude.com/docs/en/skills#skill-descriptions-are-cut-short
                                      """
                                      preferred_notif_channel: (
                                          Literal[
                                              "auto",
                                              "terminal_bell",
                                              "iterm2",
                                              "iterm2_with_bell",
                                              "kitty",
                                              "ghostty",
                                              "notifications_disabled",
                                          ]
                                          | None
                                      ) = Field("auto", alias="preferredNotifChannel")
                                      """
                                      Method for task-complete and permission-prompt notifications. "auto" (default) sends a desktop notification in iTerm2, Ghostty, and Kitty and does nothing in other terminals; "terminal_bell" rings the bell in any terminal; "notifications_disabled" turns them off. See https://code.claude.com/docs/en/terminal-config#get-a-terminal-bell-or-notification
                                      """
                                      plugin_suggestion_marketplaces: list[str] | None = Field(
                                          None, alias="pluginSuggestionMarketplaces"
                                      )
                                      """
                                      (Managed settings only) Allowlist of marketplace names whose plugins may surface as contextual "suggested for this directory" tips in the /plugin Discover tab. No marketplace-declared suggestions surface without this allowlist. The built-in first-party frontend-design tip is unaffected. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      required_maximum_version: str | None = Field(None, alias="requiredMaximumVersion")
                                      """
                                      (Managed settings only) Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup with instructions to install an approved version. See https://code.claude.com/docs/en/admin-setup#decide-what-to-enforce
                                      """
                                      required_minimum_version: str | None = Field(None, alias="requiredMinimumVersion")
                                      """
                                      (Managed settings only) Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup rather than only warning. See https://code.claude.com/docs/en/admin-setup#decide-what-to-enforce
                                      """
                                      respond_to_bash_commands: bool | None = Field(True, alias="respondToBashCommands")
                                      """
                                      Whether Claude responds after an input-box ! shell command runs (v2.1.186+). Set to false to add the command output to context without a response. See https://code.claude.com/docs/en/interactive-mode#shell-mode-with--prefix
                                      """
                                      skill_listing_budget_fraction: float | None = Field(
                                          0.01, alias="skillListingBudgetFraction", gt=0.0, le=1.0
                                      )
                                      """
                                      Fraction of the model context window reserved for the skill listing sent to Claude (default 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Also configurable via the SLASH_COMMAND_TOOL_CHAR_BUDGET environment variable (fixed character count). See https://code.claude.com/docs/en/skills#skill-descriptions-are-cut-short
                                      """
                                      ssh_configs: list[SshConfig] | None = Field(None, alias="sshConfigs")
                                      """
                                      (Managed settings) Pre-configured SSH connections distributed to Desktop users. See https://code.claude.com/docs/en/desktop#ssh-sessions
                                      """
                                      ssh_host_allowlist: list[str] | None = Field(None, alias="sshHostAllowlist")
                                      """
                                      (Managed settings only) Allowlist restricting Desktop SSH sessions to approved hosts. Patterns are case-insensitive; * matches any host and *.example.com matches example.com and any subdomain. See https://code.claude.com/docs/en/desktop#ssh-sessions
                                      """
                                      theme: (
                                          Literal[
                                              "auto",
                                              "dark",
                                              "light",
                                              "dark-daltonized",
                                              "light-daltonized",
                                              "dark-ansi",
                                              "light-ansi",
                                          ]
                                          | Theme
                                          | None
                                      ) = None
                                      """
                                      Color theme for the interface: auto, dark, light, the daltonized variants (deuteranopia-friendly), the ansi variants (16-color terminals), or a custom theme reference such as `custom:<slug>` or `custom:<plugin-name>:<slug>`. See https://code.claude.com/docs/en/terminal-config#match-the-color-theme
                                      """
                                      voice: Voice | None = None
                                      """
                                      Voice dictation settings: enabled turns dictation on, mode selects "hold" or "tap", and autoSubmit sends the prompt on key release in hold mode. Written automatically when you run /voice. Requires a Claude.ai account. See https://code.claude.com/docs/en/voice-dictation
                                      """
                                      wheel_scroll_acceleration_enabled: bool | None = Field(
                                          None, alias="wheelScrollAccelerationEnabled"
                                      )
                                      """
                                      In fullscreen rendering, accelerate mouse-wheel scroll speed during fast scrolls (v2.1.174+). Set to false for a constant scroll rate per wheel notch. See https://code.claude.com/docs/en/fullscreen#mouse-wheel-scrolling
                                      """
                                      disable_bundled_skills: bool | None = Field(None, alias="disableBundledSkills")
                                      """
                                      Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely, while built-in slash commands like /init stay typable but are hidden from the model. Skills from plugins, .claude/skills/, and .claude/commands/ are unaffected. Also configurable via the CLAUDE_CODE_DISABLE_BUNDLED_SKILLS environment variable. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      away_summary_enabled: bool | None = Field(True, alias="awaySummaryEnabled")
                                      """
                                      Show a one-line session recap when you return to the terminal after a few minutes away. Set to false (or turn off Session recap in /config) to disable. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      auto_scroll_enabled: bool | None = Field(True, alias="autoScrollEnabled")
                                      """
                                      In fullscreen rendering, follow new output to the bottom of the conversation. Appears in /config as Auto-scroll. Permission prompts still scroll into view when this is off. See https://code.claude.com/docs/en/fullscreen
                                      """
                                      allow_all_claude_ai_mcps: bool | None = Field(None, alias="allowAllClaudeAiMcps")
                                      """
                                      (Managed settings only) Load claude.ai connectors alongside a deployed managed-mcp.json, which otherwise takes exclusive control and suppresses them. See https://code.claude.com/docs/en/managed-mcp
                                      """
                                      agent_push_notif_enabled: bool | None = Field(False, alias="agentPushNotifEnabled")
                                      """
                                      When Remote Control is connected, allow Claude to send proactive push notifications to your phone, for example when a long task finishes. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/remote-control#mobile-push-notifications
                                      """
                                      ax_screen_reader: bool | None = Field(None, alias="axScreenReader")
                                      """
                                      Render screen-reader-friendly output: flat text without decorative borders or animations screen-reader mode always uses the classic renderer, so the tui setting has no effect while it is active. The CLAUDE_AX_SCREEN_READER environment variable and --ax-screen-reader flag take precedence. Requires Claude Code v2.1.181 or later. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      claude_md: str | None = Field(None, alias="claudeMd")
                                      """
                                      (Managed settings only) CLAUDE.md-style instructions injected as organization-managed memory. Honored only from managed/policy settings. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      disable_artifact: bool | None = Field(None, alias="disableArtifact")
                                      """
                                      Disable the Artifact tool, which publishes session output as a private web page on claude.ai. Also configurable via the CLAUDE_CODE_DISABLE_ARTIFACT environment variable. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      disable_auto_mode: Literal["disable"] | None = Field(None, alias="disableAutoMode")
                                      """
                                      Set to "disable" to prevent auto mode from being activated: removes auto from the Shift+Tab cycle and rejects --permission-mode auto at startup. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      disable_claude_ai_connectors: bool | None = Field(None, alias="disableClaudeAiConnectors")
                                      """
                                      Disable claude.ai MCP connectors so they are not auto-fetched or connected. A value of true in any settings source takes precedence. Requires Claude Code v2.1.182 or later. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      disable_remote_control: bool | None = Field(None, alias="disableRemoteControl")
                                      """
                                      Disable Remote Control: blocks claude remote-control, the --remote-control flag, auto-start, and the in-session toggle. Requires Claude Code v2.1.128 or later. See https://code.claude.com/docs/en/remote-control
                                      """
                                      disable_workflows: bool | None = Field(False, alias="disableWorkflows")
                                      """
                                      Disable dynamic workflows and bundled workflow commands. Also configurable via the CLAUDE_CODE_DISABLE_WORKFLOWS environment variable. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      footer_links_regexes: list[FooterLinksRegex] | None = Field(None, alias="footerLinksRegexes")
                                      """
                                      Render extra clickable badges in the footer when a regex matches turn output (tool results and assistant responses). Read from user, --settings flag, and managed settings only; ignored in project and local settings. Requires Claude Code v2.1.176 or later. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      input_needed_notif_enabled: bool | None = Field(False, alias="inputNeededNotifEnabled")
                                      """
                                      When Remote Control is connected, send a push notification to your phone when a permission prompt or question is waiting for input. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      policy_helper: PolicyHelper | None = Field(None, alias="policyHelper")
                                      """
                                      Admin-deployed executable that computes managed settings dynamically at startup. Honored only from MDM or the system managed-settings.json. Requires Claude Code v2.1.136 or later. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      remote_control_at_startup: bool | None = Field(None, alias="remoteControlAtStartup")
                                      """
                                      Connect Remote Control automatically when each interactive session starts. true = always, false = never, unset = organization default. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/remote-control#enable-remote-control-for-all-sessions
                                      """
                                      syntax_highlighting_disabled: bool | None = Field(None, alias="syntaxHighlightingDisabled")
                                      """
                                      Disable syntax highlighting in diffs, code blocks, and file previews. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      verbose: bool | None = False
                                      """
                                      Show full tool output instead of truncated summaries. The --verbose flag overrides this for a single session. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      workflow_keyword_trigger_enabled: bool | None = Field(
                                          True, alias="workflowKeywordTriggerEnabled"
                                      )
                                      """
                                      Whether including the keyword "ultracode" in a prompt triggers a dynamic workflow. Requires Claude Code v2.1.157 or later. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      ask_user_question_timeout: Literal["60s", "5m", "10m", "never"] | None = Field(
                                          "never", alias="askUserQuestionTimeout"
                                      )
                                      """
                                      Idle time before an unanswered AskUserQuestion dialog auto-continues with whatever options you had already selected. Accepts "60s", "5m", "10m", or "never" (default: "never", which waits until you answer). Appears in /config as Question auto-continue timeout, which writes this key to user settings. Not read from project or local settings. Requires Claude Code v2.1.200 or later. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      teammate_default_model: str | None = Field(
                                          None, alias="teammateDefaultModel", examples=["sonnet"]
                                      )
                                      """
                                      Default model for agent team teammates when the spawn prompt does not specify one. Set to a model alias such as "sonnet", or null to inherit the lead's current /model selection. Appears in /config as Default teammate model. See https://code.claude.com/docs/en/agent-teams
                                      """
                                      workflow_size_guideline: Literal["unrestricted", "small", "medium", "large"] | None = Field(
                                          "unrestricted", alias="workflowSizeGuideline"
                                      )
                                      """
                                      Sets the agent count Claude aims for in the dynamic workflows it writes. Claude Code sends the value to Claude as advice, not an enforced cap. Accepts "unrestricted" (default, which sends no guideline), "small", "medium", or "large". Appears in /config as Dynamic workflow size, and can be set with /config workflowSizeGuideline=small. Requires Claude Code v2.1.202 or later. On v2.1.203 or later the guideline's agent count also replaces the default threshold for the Large workflow warning. See https://code.claude.com/docs/en/workflows#set-a-size-guideline
                                      """
                                      enable_artifact: bool | None = Field(None, alias="enableArtifact")
                                      """
                                      Enable or disable the Artifact tool for this user. When unset, the default follows the feature's availability for your account. The Artifacts row in /config writes this key. A managed disableArtifact and your organization's admin setting take precedence, and the key is ignored in project and local settings (.claude/settings.json, .claude/settings.local.json), which a repository could otherwise commit. Requires Claude Code v2.1.196 or later. See https://code.claude.com/docs/en/artifacts
                                      """
                                      permission_explainer_enabled: bool | None = Field(True, alias="permissionExplainerEnabled")
                                      """
                                      Show a model-generated explanation of the command when you press Ctrl+E on a Bash or PowerShell permission prompt (default: true). Set to false to turn the shortcut off. See https://code.claude.com/docs/en/permissions#permission-system
                                      """
                                      diff_tool: Literal["auto", "terminal"] | None = Field("auto", alias="diffTool")
                                      """
                                      Where to display file diffs when an IDE is connected: "auto" (default) opens diffs in the IDE's diff viewer, "terminal" keeps them in the terminal. Appears in /config as Diff tool only when Claude Code is connected to a VS Code or JetBrains IDE. See https://code.claude.com/docs/en/settings#global-config-settings
                                      """
                                      external_editor_context: bool | None = Field(False, alias="externalEditorContext")
                                      """
                                      Prepend Claude's previous response as #-commented context when you open the external editor with Ctrl+G (default: false). Appears in /config as Show last response in external editor. See https://code.claude.com/docs/en/settings#global-config-settings
                                      """
                                      auto_connect_ide: bool | None = Field(False, alias="autoConnectIde")
                                      """
                                      Automatically connect to a running IDE when Claude Code starts from an external terminal (default: false). Appears in /config as Auto-connect to IDE (external terminal) when running outside a VS Code or JetBrains terminal. Also configurable via the CLAUDE_CODE_AUTO_CONNECT_IDE environment variable, which overrides this when set. See https://code.claude.com/docs/en/settings#global-config-settings
                                      """
                                      auto_install_ide_extension: bool | None = Field(True, alias="autoInstallIdeExtension")
                                      """
                                      Automatically install the Claude Code IDE extension when running from a VS Code terminal (default: true). Appears in /config as Auto-install IDE extension when running inside a VS Code or JetBrains terminal. You can also set the CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL environment variable to 1. See https://code.claude.com/docs/en/settings#global-config-settings
                                      """
                                      emoji_completion_enabled: bool | None = Field(True, alias="emojiCompletionEnabled")
                                      """
                                      Show emoji suggestions when you type : plus a shortcode in the prompt input, and replace a completed shortcode such as :heart: with its emoji (default: true). Set to false to disable both. Requires Claude Code v2.1.217 or later. See https://code.claude.com/docs/en/interactive-mode#emoji-shortcodes
                                      """
                                      vim_insert_mode_remaps: dict[str, str] | None = Field(
                                          None, alias="vimInsertModeRemaps", examples=[{"jj": "<Esc>"}]
                                      )
                                      """
                                      Map two-key INSERT-mode sequences to Escape in vim editor mode. Each key is exactly two printable characters typed in sequence, and `<Esc>` is the only supported target; other entries are ignored. Read from user, --settings flag, and managed settings only, so a repository's checked-in settings cannot remap your keystrokes. Has no effect unless editorMode is "vim". Requires Claude Code v2.1.208 or later. See https://code.claude.com/docs/en/interactive-mode#remap-insert-mode-key-sequences
                                      """
                                      process_wrapper: str | None = Field(
                                          None, alias="processWrapper", examples=["/opt/corp/launcher --profile claude"]
                                      )
                                      """
                                      Corporate launcher command placed in front of the background processes Claude Code starts. Honored from managed settings, a --settings file, and user settings only; the CLAUDE_CODE_PROCESS_WRAPPER environment variable takes precedence when both are set. Requires Claude Code v2.1.210 or later. See https://code.claude.com/docs/en/corporate-launcher
                                      """
                                      force_login_gateway_url: str | None = Field(
                                          None, alias="forceLoginGatewayUrl", examples=["https://claude-gateway.example.com"]
                                      )
                                      """
                                      Pre-fills and locks the gateway URL on the /login Cloud gateway screen. Either this key or forceLoginMethod: "gateway" surfaces that screen; set both so the URL is filled in. Honored only at the managed policy tier; ignored in user and project settings. See https://code.claude.com/docs/en/claude-apps-gateway#set-the-gateway-url
                                      """
                                      disable_sideload_flags: bool | None = Field(None, alias="disableSideloadFlags")
                                      """
                                      (Managed settings only) Reject the --plugin-dir, --plugin-url, --agents, and --mcp-config CLI flags at startup, which users could otherwise pass to bypass strictKnownMarketplaces for a single run. Also rejects these flags from any surface that spawns the CLI with them internally, currently Cowork local sessions in the desktop app. A --mcp-config whose servers are all in-process type: "sdk" entries is still accepted, so the Agent SDK and VS Code extension keep working. Does not block claude mcp add, .mcp.json, or SDK setMcpServers(); pair with allowedMcpServers for per-server MCP control. Requires Claude Code v2.1.193 or later. See https://code.claude.com/docs/en/settings#available-settings
                                      """
                                      browser_external_page_tools: Literal["disabled"] | None = Field(
                                          None, alias="browserExternalPageTools"
                                      )
                                      """
                                      (Managed settings only) Set to "disabled" to prevent Claude from using tools to read or act on external pages in the desktop app's Browser pane. Users can still navigate to external sites themselves, and local dev server previews are unaffected. See https://code.claude.com/docs/en/desktop#browse-external-sites
                                      """
                                      disable_browser_external_navigation: bool | None = Field(
                                          None, alias="disableBrowserExternalNavigation"
                                      )
                                      """
                                      (Managed settings only) Set to true to turn off external browsing in the desktop app's Browser pane. Neither users nor Claude can navigate to external sites, and localhost dev server previews are unaffected. The value must be the JSON boolean true; the string "true" is ignored. See https://code.claude.com/docs/en/desktop#browse-external-sites
                                      """
                                      disable_mobile_simulator_tools: bool | None = Field(None, alias="disableMobileSimulatorTools")
                                      """
                                      (Managed settings only) Set to true to block Claude's tools for the desktop app's iOS Simulator pane. Users keep manual use of the pane; only Claude's access is removed. The value must be the JSON boolean true; any other value is ignored, and a malformed value such as "true" or 1 logs a warning. See https://code.claude.com/docs/en/desktop-ios-simulator#turn-off-simulator-access
                                      """
                                      require_cowork_full_vm_sandbox: bool | None = Field(None, alias="requireCoworkFullVmSandbox")
                                      """
                                      (Managed settings only) Run Claude's tools inside an isolated virtual machine instead of on your Mac. Disables the desktop app's iOS Simulator pane and Claude's simulator tools entirely, so the pane cannot attach a device while it is set. See https://code.claude.com/docs/en/desktop-ios-simulator#turn-off-simulator-access
                                      """
                                  

                                  advisor_model class-attribute instance-attribute

                                  advisor_model: str | None = Field(None, alias='advisorModel')
                                  

                                  Model for the server-side advisor tool. Accepts a model alias ("opus", "sonnet", or "fable" on v2.1.170+) or a full model ID. Overridden by the --advisor CLI flag for the session, and blocked when the model is outside the availableModels allowlist. See https://code.claude.com/docs/en/advisor

                                  agent class-attribute instance-attribute

                                  agent: str | None = Field(None, min_length=1)
                                  

                                  Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model. See https://code.claude.com/docs/en/sub-agents

                                  agent_push_notif_enabled class-attribute instance-attribute

                                  agent_push_notif_enabled: bool | None = Field(False, alias='agentPushNotifEnabled')
                                  

                                  When Remote Control is connected, allow Claude to send proactive push notifications to your phone, for example when a long task finishes. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/remote-control#mobile-push-notifications

                                  allow_all_claude_ai_mcps class-attribute instance-attribute

                                  allow_all_claude_ai_mcps: bool | None = Field(None, alias='allowAllClaudeAiMcps')
                                  

                                  (Managed settings only) Load claude.ai connectors alongside a deployed managed-mcp.json, which otherwise takes exclusive control and suppresses them. See https://code.claude.com/docs/en/managed-mcp

                                  allow_managed_hooks_only class-attribute instance-attribute

                                  allow_managed_hooks_only: bool | None = Field(None, alias='allowManagedHooksOnly')
                                  

                                  (Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See https://code.claude.com/docs/en/settings#hook-configuration

                                  allow_managed_mcp_servers_only class-attribute instance-attribute

                                  allow_managed_mcp_servers_only: bool | None = Field(None, alias='allowManagedMcpServersOnly')
                                  

                                  (Managed settings only) When true, only allowedMcpServers from managed settings are respected; MCP servers defined in user, project, or local settings are ignored. deniedMcpServers still merges from all sources. See https://code.claude.com/docs/en/managed-mcp

                                  allow_managed_permission_rules_only class-attribute instance-attribute

                                  allow_managed_permission_rules_only: bool | None = Field(
                                      None, alias="allowManagedPermissionRulesOnly"
                                  )
                                  

                                  (Managed settings only) Prevent user and project settings from defining allow, ask, or deny permission rules. Only rules in managed settings apply. See https://code.claude.com/docs/en/settings#permission-settings

                                  allowed_channel_plugins class-attribute instance-attribute

                                  allowed_channel_plugins: list[AllowedChannelPlugin] | None = Field(
                                      None, alias="allowedChannelPlugins"
                                  )
                                  

                                  (Managed settings only) Allowlist of channel plugins that may run, each identified by its marketplace and plugin name. When set, only the listed plugins can push inbound channel messages while channelsEnabled is true. Replaces the default Anthropic allowlist when set; undefined falls back to the default and an empty array blocks all channel plugins. Requires channelsEnabled: true. See https://code.claude.com/docs/en/channels#restrict-which-channel-plugins-can-run

                                  allowed_http_hook_urls class-attribute instance-attribute

                                  allowed_http_hook_urls: list[AllowedHttpHookUrl] | None = Field(
                                      None,
                                      alias="allowedHttpHookUrls",
                                      examples=[["https://hooks.example.com/*", "http://localhost:*"]],
                                  )
                                  

                                  Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration

                                  allowed_mcp_servers class-attribute instance-attribute

                                  allowed_mcp_servers: (
                                      list[
                                          AllowedMcpServerByServerName | AllowedMcpServerByServerCommand | AllowedMcpServerByServerUrl
                                      ]
                                      | None
                                  ) = Field(None, alias="allowedMcpServers")
                                  

                                  Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options

                                  always_thinking_enabled class-attribute instance-attribute

                                  always_thinking_enabled: bool | None = Field(None, alias='alwaysThinkingEnabled')
                                  

                                  Enable extended thinking by default for all sessions. Typically configured via the /config command rather than editing directly. See https://code.claude.com/docs/en/common-workflows#use-extended-thinking-thinking-mode

                                  api_key_helper class-attribute instance-attribute

                                  api_key_helper: str | None = Field(
                                      None, alias="apiKeyHelper", examples=["/bin/generate_temp_api_key.sh"], min_length=1
                                  )
                                  

                                  Path to a script that outputs authentication values. See https://code.claude.com/docs/en/settings#available-settings

                                  ask_user_question_timeout class-attribute instance-attribute

                                  ask_user_question_timeout: Literal["60s", "5m", "10m", "never"] | None = Field(
                                      "never", alias="askUserQuestionTimeout"
                                  )
                                  

                                  Idle time before an unanswered AskUserQuestion dialog auto-continues with whatever options you had already selected. Accepts "60s", "5m", "10m", or "never" (default: "never", which waits until you answer). Appears in /config as Question auto-continue timeout, which writes this key to user settings. Not read from project or local settings. Requires Claude Code v2.1.200 or later. See https://code.claude.com/docs/en/settings#available-settings

                                  attribution class-attribute instance-attribute

                                  attribution: Attribution | None = None
                                  

                                  Customize attribution for git commits and pull requests. See https://code.claude.com/docs/en/settings#attribution-settings

                                  auto_compact_enabled class-attribute instance-attribute

                                  auto_compact_enabled: bool | None = Field(True, alias='autoCompactEnabled')
                                  

                                  Automatically compact the conversation when context approaches the limit. Also configurable via the DISABLE_AUTO_COMPACT environment variable. See https://code.claude.com/docs/en/settings#available-settings

                                  auto_connect_ide class-attribute instance-attribute

                                  auto_connect_ide: bool | None = Field(False, alias='autoConnectIde')
                                  

                                  Automatically connect to a running IDE when Claude Code starts from an external terminal (default: false). Appears in /config as Auto-connect to IDE (external terminal) when running outside a VS Code or JetBrains terminal. Also configurable via the CLAUDE_CODE_AUTO_CONNECT_IDE environment variable, which overrides this when set. See https://code.claude.com/docs/en/settings#global-config-settings

                                  auto_install_ide_extension class-attribute instance-attribute

                                  auto_install_ide_extension: bool | None = Field(True, alias='autoInstallIdeExtension')
                                  

                                  Automatically install the Claude Code IDE extension when running from a VS Code terminal (default: true). Appears in /config as Auto-install IDE extension when running inside a VS Code or JetBrains terminal. You can also set the CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL environment variable to 1. See https://code.claude.com/docs/en/settings#global-config-settings

                                  auto_memory_directory class-attribute instance-attribute

                                  auto_memory_directory: str | None = Field(None, alias='autoMemoryDirectory', min_length=1)
                                  

                                  Custom directory path for auto-memory storage. Supports ~/ prefix for home-directory expansion. Ignored if set in checked-in project settings (.claude/settings.json) for security. Defaults to ~/.claude/projects/<sanitized-cwd>/memory/ when unset. See https://code.claude.com/docs/en/memory

                                  auto_memory_enabled class-attribute instance-attribute

                                  auto_memory_enabled: bool | None = Field(True, alias='autoMemoryEnabled')
                                  

                                  Enable automatic memory saves that capture useful context to ~/.claude/projects/<project>/memory/ (derived from the git repository, shared across worktrees). Also configurable via CLAUDE_CODE_DISABLE_AUTO_MEMORY environment variable (set to 1 to disable, 0 to enable). See https://code.claude.com/docs/en/memory#storage-location

                                  auto_mode class-attribute instance-attribute

                                  auto_mode: AutoMode | None = Field(None, alias='autoMode')
                                  

                                  Customization for the auto mode classifier prompt. Typically configured in managed settings to tune the allow/deny rules used when permissions.defaultMode is "auto". By default, allow, soft_deny, and environment REPLACE the corresponding built-in classifier section entirely. Include the literal string "$defaults" as an array entry (added in v2.1.118) to splice the built-in defaults in at that position alongside your custom rules. See https://code.claude.com/docs/en/permissions

                                  auto_scroll_enabled class-attribute instance-attribute

                                  auto_scroll_enabled: bool | None = Field(True, alias='autoScrollEnabled')
                                  

                                  In fullscreen rendering, follow new output to the bottom of the conversation. Appears in /config as Auto-scroll. Permission prompts still scroll into view when this is off. See https://code.claude.com/docs/en/fullscreen

                                  auto_updates_channel class-attribute instance-attribute

                                  auto_updates_channel: Literal["stable", "latest"] | None = Field(
                                      "latest", alias="autoUpdatesChannel"
                                  )
                                  

                                  Release channel to follow for updates. Use "stable" for a version that is typically about one week old and skips versions with major regressions, or "latest" (default) for the most recent release. Set DISABLE_AUTOUPDATER=1 to disable background auto-updates, or DISABLE_UPDATES=1 (added in v2.1.118) to block all update paths including manual claude update.

                                  available_models class-attribute instance-attribute

                                  available_models: list[str] | None = Field(
                                      None, alias="availableModels", examples=[["sonnet", "haiku"]]
                                  )
                                  

                                  Restrict which models users can select. When defined at multiple settings levels (user, project, etc.), arrays are merged and deduplicated. See https://code.claude.com/docs/en/model-config#restrict-model-selection

                                  away_summary_enabled class-attribute instance-attribute

                                  away_summary_enabled: bool | None = Field(True, alias='awaySummaryEnabled')
                                  

                                  Show a one-line session recap when you return to the terminal after a few minutes away. Set to false (or turn off Session recap in /config) to disable. See https://code.claude.com/docs/en/settings#available-settings

                                  aws_auth_refresh class-attribute instance-attribute

                                  aws_auth_refresh: str | None = Field(
                                      None, alias="awsAuthRefresh", examples=["aws sso login --profile myprofile"], min_length=1
                                  )
                                  

                                  Command to run when AWS credentials are expired or unavailable; its output is shown to the user but interactive input is not supported. Also drives the "Claude Platform on AWS · refresh credentials" option in /login when configured. See https://code.claude.com/docs/en/amazon-bedrock#advanced-credential-configuration

                                  aws_credential_export class-attribute instance-attribute

                                  aws_credential_export: str | None = Field(
                                      None, alias="awsCredentialExport", examples=["/bin/generate_aws_grant.sh"], min_length=1
                                  )
                                  

                                  Command that outputs AWS credentials as JSON (in the form {"Credentials": {"AccessKeyId": ..., "SecretAccessKey": ..., "SessionToken": ...}}). The output is captured silently. Use when you cannot modify the .aws directory and must return credentials directly. See https://code.claude.com/docs/en/amazon-bedrock#advanced-credential-configuration

                                  ax_screen_reader class-attribute instance-attribute

                                  ax_screen_reader: bool | None = Field(None, alias='axScreenReader')
                                  

                                  Render screen-reader-friendly output: flat text without decorative borders or animations screen-reader mode always uses the classic renderer, so the tui setting has no effect while it is active. The CLAUDE_AX_SCREEN_READER environment variable and --ax-screen-reader flag take precedence. Requires Claude Code v2.1.181 or later. See https://code.claude.com/docs/en/settings#available-settings

                                  blocked_marketplaces class-attribute instance-attribute

                                  (Managed settings only) Blocklist of marketplace sources. These exact sources are blocked from being added as marketplaces. The check happens before downloading, so blocked sources never touch the filesystem.

                                  browser_external_page_tools class-attribute instance-attribute

                                  browser_external_page_tools: Literal["disabled"] | None = Field(
                                      None, alias="browserExternalPageTools"
                                  )
                                  

                                  (Managed settings only) Set to "disabled" to prevent Claude from using tools to read or act on external pages in the desktop app's Browser pane. Users can still navigate to external sites themselves, and local dev server previews are unaffected. See https://code.claude.com/docs/en/desktop#browse-external-sites

                                  channels_enabled class-attribute instance-attribute

                                  channels_enabled: bool | None = Field(None, alias='channelsEnabled')
                                  

                                  (Managed settings only) Allow channels for the organization. On claude.ai Team and Enterprise plans, channels are blocked when this is unset or false. For Anthropic Console accounts using API key authentication, channels are allowed by default unless the organization deploys managed settings, in which case this key must be set to true. See https://code.claude.com/docs/en/channels#enterprise-controls

                                  claude_md class-attribute instance-attribute

                                  claude_md: str | None = Field(None, alias='claudeMd')
                                  

                                  (Managed settings only) CLAUDE.md-style instructions injected as organization-managed memory. Honored only from managed/policy settings. See https://code.claude.com/docs/en/settings#available-settings

                                  claude_md_excludes class-attribute instance-attribute

                                  claude_md_excludes: list[ClaudeMdExclude] | None = Field(
                                      None,
                                      alias="claudeMdExcludes",
                                      examples=[["**/monorepo/CLAUDE.md", "/home/user/monorepo/other-team/.claude/rules/**"]],
                                  )
                                  

                                  Glob patterns for CLAUDE.md files to exclude from loading. Useful in monorepos to skip irrelevant instructions from other teams. Patterns match against absolute file paths. Arrays merge across settings layers. Managed policy CLAUDE.md files cannot be excluded. See https://code.claude.com/docs/en/memory#exclude-specific-claude-md-files

                                  cleanup_period_days class-attribute instance-attribute

                                  cleanup_period_days: int | None = Field(30, alias="cleanupPeriodDays", examples=[20, 30, 60], ge=1)
                                  

                                  Number of days to retain sessions, orphaned subagent worktrees, tasks, shell snapshots, and backups. Minimum is 1; setting 0 is rejected with a validation error. See https://code.claude.com/docs/en/settings#available-settings

                                  company_announcements class-attribute instance-attribute

                                  company_announcements: list[CompanyAnnouncement] | None = Field(None, alias='companyAnnouncements')
                                  

                                  Company announcements to display at startup (one will be randomly selected if multiple are provided)

                                  default_shell class-attribute instance-attribute

                                  default_shell: Literal['bash', 'powershell'] | None = Field(None, alias='defaultShell')
                                  

                                  Default shell for input-box ! commands. Default: bash. Using "powershell" routes ! commands through PowerShell on Windows and requires CLAUDE_CODE_USE_POWERSHELL_TOOL=1 with pwsh on PATH. See https://code.claude.com/docs/en/settings#available-settings

                                  denied_mcp_servers class-attribute instance-attribute

                                  denied_mcp_servers: (
                                      list[DeniedMcpServerByServerName | DeniedMcpServerByServerCommand | DeniedMcpServerByServerUrl]
                                      | None
                                  ) = Field(None, alias="deniedMcpServers")
                                  

                                  Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options

                                  diff_tool class-attribute instance-attribute

                                  diff_tool: Literal['auto', 'terminal'] | None = Field('auto', alias='diffTool')
                                  

                                  Where to display file diffs when an IDE is connected: "auto" (default) opens diffs in the IDE's diff viewer, "terminal" keeps them in the terminal. Appears in /config as Diff tool only when Claude Code is connected to a VS Code or JetBrains IDE. See https://code.claude.com/docs/en/settings#global-config-settings

                                  disable_agent_view class-attribute instance-attribute

                                  disable_agent_view: bool | None = Field(None, alias='disableAgentView')
                                  

                                  (Managed settings) Turn off background agents and the agent view: claude agents, --bg, /background, and the on-demand supervisor. Also configurable via the CLAUDE_CODE_DISABLE_AGENT_VIEW environment variable (set to 1 to disable). See https://code.claude.com/docs/en/agent-view

                                  disable_all_hooks class-attribute instance-attribute

                                  disable_all_hooks: bool | None = Field(None, alias='disableAllHooks')
                                  

                                  Disable all hooks and statusLine execution. When true in managed settings, user and project-level disableAllHooks cannot override it. See https://code.claude.com/docs/en/hooks#disable-or-remove-hooks

                                  disable_artifact class-attribute instance-attribute

                                  disable_artifact: bool | None = Field(None, alias='disableArtifact')
                                  

                                  Disable the Artifact tool, which publishes session output as a private web page on claude.ai. Also configurable via the CLAUDE_CODE_DISABLE_ARTIFACT environment variable. See https://code.claude.com/docs/en/settings#available-settings

                                  disable_auto_mode class-attribute instance-attribute

                                  disable_auto_mode: Literal['disable'] | None = Field(None, alias='disableAutoMode')
                                  

                                  Set to "disable" to prevent auto mode from being activated: removes auto from the Shift+Tab cycle and rejects --permission-mode auto at startup. See https://code.claude.com/docs/en/settings#available-settings

                                  disable_browser_external_navigation class-attribute instance-attribute

                                  disable_browser_external_navigation: bool | None = Field(
                                      None, alias="disableBrowserExternalNavigation"
                                  )
                                  

                                  (Managed settings only) Set to true to turn off external browsing in the desktop app's Browser pane. Neither users nor Claude can navigate to external sites, and localhost dev server previews are unaffected. The value must be the JSON boolean true; the string "true" is ignored. See https://code.claude.com/docs/en/desktop#browse-external-sites

                                  disable_bundled_skills class-attribute instance-attribute

                                  disable_bundled_skills: bool | None = Field(None, alias='disableBundledSkills')
                                  

                                  Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely, while built-in slash commands like /init stay typable but are hidden from the model. Skills from plugins, .claude/skills/, and .claude/commands/ are unaffected. Also configurable via the CLAUDE_CODE_DISABLE_BUNDLED_SKILLS environment variable. See https://code.claude.com/docs/en/settings#available-settings

                                  disable_claude_ai_connectors class-attribute instance-attribute

                                  disable_claude_ai_connectors: bool | None = Field(None, alias='disableClaudeAiConnectors')
                                  

                                  Disable claude.ai MCP connectors so they are not auto-fetched or connected. A value of true in any settings source takes precedence. Requires Claude Code v2.1.182 or later. See https://code.claude.com/docs/en/settings#available-settings

                                  disable_deep_link_registration: Literal["disable"] | None = Field(
                                      None, alias="disableDeepLinkRegistration"
                                  )
                                  

                                  Set to "disable" to prevent Claude Code from registering the claude-cli:// deep-link protocol handler on startup. Most useful in managed settings where users cannot override it. See https://code.claude.com/docs/en/settings#available-settings

                                  disable_mobile_simulator_tools class-attribute instance-attribute

                                  disable_mobile_simulator_tools: bool | None = Field(None, alias='disableMobileSimulatorTools')
                                  

                                  (Managed settings only) Set to true to block Claude's tools for the desktop app's iOS Simulator pane. Users keep manual use of the pane; only Claude's access is removed. The value must be the JSON boolean true; any other value is ignored, and a malformed value such as "true" or 1 logs a warning. See https://code.claude.com/docs/en/desktop-ios-simulator#turn-off-simulator-access

                                  disable_remote_control class-attribute instance-attribute

                                  disable_remote_control: bool | None = Field(None, alias='disableRemoteControl')
                                  

                                  Disable Remote Control: blocks claude remote-control, the --remote-control flag, auto-start, and the in-session toggle. Requires Claude Code v2.1.128 or later. See https://code.claude.com/docs/en/remote-control

                                  disable_sideload_flags class-attribute instance-attribute

                                  disable_sideload_flags: bool | None = Field(None, alias='disableSideloadFlags')
                                  

                                  (Managed settings only) Reject the --plugin-dir, --plugin-url, --agents, and --mcp-config CLI flags at startup, which users could otherwise pass to bypass strictKnownMarketplaces for a single run. Also rejects these flags from any surface that spawns the CLI with them internally, currently Cowork local sessions in the desktop app. A --mcp-config whose servers are all in-process type: "sdk" entries is still accepted, so the Agent SDK and VS Code extension keep working. Does not block claude mcp add, .mcp.json, or SDK setMcpServers(); pair with allowedMcpServers for per-server MCP control. Requires Claude Code v2.1.193 or later. See https://code.claude.com/docs/en/settings#available-settings

                                  disable_skill_shell_execution class-attribute instance-attribute

                                  disable_skill_shell_execution: bool | None = Field(None, alias='disableSkillShellExecution')
                                  

                                  Disable inline shell execution for !`...` and ```! blocks in skills and custom slash commands from user, project, plugin, or additional-directory sources. Commands are replaced with [shell command execution disabled by policy] instead of being run. Bundled and managed skills are not affected. Most useful in managed settings where users cannot override it. See https://code.claude.com/docs/en/settings#available-settings

                                  disable_workflows class-attribute instance-attribute

                                  disable_workflows: bool | None = Field(False, alias='disableWorkflows')
                                  

                                  Disable dynamic workflows and bundled workflow commands. Also configurable via the CLAUDE_CODE_DISABLE_WORKFLOWS environment variable. See https://code.claude.com/docs/en/settings#available-settings

                                  disabled_mcpjson_servers class-attribute instance-attribute

                                  disabled_mcpjson_servers: list[DisabledMcpjsonServer] | None = Field(
                                      None, alias="disabledMcpjsonServers", examples=[["filesystem"]]
                                  )
                                  

                                  List of rejected MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp

                                  editor_mode class-attribute instance-attribute

                                  editor_mode: Literal['normal', 'vim'] | None = Field('normal', alias='editorMode')
                                  

                                  Key binding mode for the input prompt: "normal" or "vim". Appears in /config as Editor mode. See https://code.claude.com/docs/en/terminal-config#edit-prompts-with-vim-keybindings

                                  effort_level class-attribute instance-attribute

                                  effort_level: Literal["low", "medium", "high", "xhigh", "max"] | None = Field(
                                      None, alias="effortLevel"
                                  )
                                  

                                  Persist adaptive reasoning effort across sessions. Set to low, medium, high, or xhigh; max and ultracode are session-only and are not accepted in the settings file (use the CLAUDE_CODE_EFFORT_LEVEL environment variable or /effort for a session-only max). Effort is supported on Fable 5, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6, with xhigh sitting between high and max (added in v2.1.111). Defaults: Fable 5 and Opus 4.8 default to high; Opus 4.6 and Sonnet 4.6 default to high on all plans (Pro/Max raised from medium to high in v2.1.117); Opus 4.7 defaults to xhigh. Use /effort auto to reset to model default. Also configurable via CLAUDE_CODE_EFFORT_LEVEL environment variable. See https://code.claude.com/docs/en/model-config#adjust-effort-level

                                  emoji_completion_enabled class-attribute instance-attribute

                                  emoji_completion_enabled: bool | None = Field(True, alias='emojiCompletionEnabled')
                                  

                                  Show emoji suggestions when you type : plus a shortcode in the prompt input, and replace a completed shortcode such as ❤️ with its emoji (default: true). Set to false to disable both. Requires Claude Code v2.1.217 or later. See https://code.claude.com/docs/en/interactive-mode#emoji-shortcodes

                                  enable_all_project_mcp_servers class-attribute instance-attribute

                                  enable_all_project_mcp_servers: bool | None = Field(
                                      None, alias="enableAllProjectMcpServers", examples=[True]
                                  )
                                  

                                  Whether to automatically approve all MCP servers in the project. See https://code.claude.com/docs/en/mcp

                                  enable_artifact class-attribute instance-attribute

                                  enable_artifact: bool | None = Field(None, alias='enableArtifact')
                                  

                                  Enable or disable the Artifact tool for this user. When unset, the default follows the feature's availability for your account. The Artifacts row in /config writes this key. A managed disableArtifact and your organization's admin setting take precedence, and the key is ignored in project and local settings (.claude/settings.json, .claude/settings.local.json), which a repository could otherwise commit. Requires Claude Code v2.1.196 or later. See https://code.claude.com/docs/en/artifacts

                                  enabled_mcpjson_servers class-attribute instance-attribute

                                  enabled_mcpjson_servers: list[EnabledMcpjsonServer] | None = Field(
                                      None, alias="enabledMcpjsonServers", examples=[["memory", "github"]]
                                  )
                                  

                                  List of approved MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp

                                  enabled_plugins class-attribute instance-attribute

                                  enabled_plugins: dict[str, list[str] | bool | Any] | None = Field(None, alias='enabledPlugins')
                                  

                                  Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. See https://code.claude.com/docs/en/plugins

                                  enforce_available_models class-attribute instance-attribute

                                  enforce_available_models: bool | None = Field(None, alias='enforceAvailableModels')
                                  

                                  (Managed settings) Extend the availableModels allowlist to the Default model option (requires v2.1.175+). Requires a non-empty availableModels list; when the account-type default is not in the allowlist, Default resolves to the first allowed entry instead. Has no effect when availableModels is unset or empty. See https://code.claude.com/docs/en/model-config#enforce-the-allowlist-for-the-default-model

                                  env class-attribute instance-attribute

                                  env: Env | None = Field(
                                      default_factory=lambda: Env.model_validate({}),
                                      examples=[
                                          {
                                              "ANTHROPIC_MODEL": "claude-opus-4-1",
                                              "ANTHROPIC_SMALL_FAST_MODEL": "claude-3-5-haiku-latest",
                                          }
                                      ],
                                  )
                                  

                                  Environment variables to set for Claude Code sessions. Many environment variables provide settings dimensions not available as dedicated settings.json properties (e.g., thinking tokens, prompt caching, bash timeouts, shell configuration). See https://code.claude.com/docs/en/settings#environment-variables for the full list.

                                  external_editor_context class-attribute instance-attribute

                                  external_editor_context: bool | None = Field(False, alias='externalEditorContext')
                                  

                                  Prepend Claude's previous response as #-commented context when you open the external editor with Ctrl+G (default: false). Appears in /config as Show last response in external editor. See https://code.claude.com/docs/en/settings#global-config-settings

                                  extra_known_marketplaces class-attribute instance-attribute

                                  extra_known_marketplaces: dict[str, ExtraKnownMarketplaces] | None = Field(
                                      None, alias="extraKnownMarketplaces"
                                  )
                                  

                                  Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources. See https://code.claude.com/docs/en/plugin-marketplaces

                                  fallback_model class-attribute instance-attribute

                                  fallback_model: list[str] | None = Field(None, alias='fallbackModel', max_length=3)
                                  

                                  Fallback model chain tried in order when the primary model is overloaded, unavailable, or returns a non-retryable server error. Capped at three entries after deduplication; accepts model names or aliases, and "default" expands to the account-type default. Overridden by the --fallback-model CLI flag for the session. See https://code.claude.com/docs/en/model-config#fallback-model-chains

                                  fast_mode class-attribute instance-attribute

                                  fast_mode: bool | None = Field(False, alias='fastMode')
                                  

                                  Enable fast mode, which uses Claude Opus 5 by default (since v2.1.219) for faster output at higher per-token cost without downgrading to a smaller model. Requires extra usage enabled. Toggle with the /fast command. Supported on Opus 5 and Opus 4.8; fast mode for Opus 4.7 was deprecated on June 25, 2026 and removed on July 24, 2026. Before v2.1.219 fast mode defaulted to Opus 4.8 (v2.1.154 through v2.1.218) and to Opus 4.7 (v2.1.142 through v2.1.153). See https://code.claude.com/docs/en/fast-mode

                                  fast_mode_per_session_opt_in class-attribute instance-attribute

                                  fast_mode_per_session_opt_in: bool | None = Field(False, alias='fastModePerSessionOptIn')
                                  

                                  Require per-session opt-in for fast mode. When true, fast mode does not persist across sessions and users must enable it with /fast each session. Useful for controlling costs. See https://code.claude.com/docs/en/fast-mode

                                  feedback_survey_rate class-attribute instance-attribute

                                  feedback_survey_rate: float | None = Field(
                                      None, alias="feedbackSurveyRate", examples=[0.05], ge=0.0, le=1.0
                                  )
                                  

                                  Probability (0–1) that the session quality survey appears when eligible. A value of 0.05 means 5% of eligible sessions. See https://code.claude.com/docs/en/settings#available-settings

                                  field_schema class-attribute instance-attribute

                                  field_schema: str | None = Field(None, alias='$schema')
                                  

                                  JSON Schema reference for Claude Code settings

                                  file_checkpointing_enabled class-attribute instance-attribute

                                  file_checkpointing_enabled: bool | None = Field(True, alias='fileCheckpointingEnabled')
                                  

                                  Snapshot edited files so /rewind can restore them. Also configurable via the CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING environment variable (set to 1 to disable). See https://code.claude.com/docs/en/checkpointing

                                  file_suggestion class-attribute instance-attribute

                                  file_suggestion: FileSuggestion | None = Field(
                                      None,
                                      alias="fileSuggestion",
                                      examples=[{"type": "command", "command": "~/.claude/file-suggestion.sh"}],
                                  )
                                  

                                  Configure a custom script for @ file autocomplete. See https://code.claude.com/docs/en/settings#file-suggestion-settings

                                  footer_links_regexes: list[FooterLinksRegex] | None = Field(None, alias='footerLinksRegexes')
                                  

                                  Render extra clickable badges in the footer when a regex matches turn output (tool results and assistant responses). Read from user, --settings flag, and managed settings only; ignored in project and local settings. Requires Claude Code v2.1.176 or later. See https://code.claude.com/docs/en/settings#available-settings

                                  force_login_gateway_url class-attribute instance-attribute

                                  force_login_gateway_url: str | None = Field(
                                      None, alias="forceLoginGatewayUrl", examples=["https://claude-gateway.example.com"]
                                  )
                                  

                                  Pre-fills and locks the gateway URL on the /login Cloud gateway screen. Either this key or forceLoginMethod: "gateway" surfaces that screen; set both so the URL is filled in. Honored only at the managed policy tier; ignored in user and project settings. See https://code.claude.com/docs/en/claude-apps-gateway#set-the-gateway-url

                                  force_login_method class-attribute instance-attribute

                                  force_login_method: Literal["claudeai", "console", "gateway"] | None = Field(
                                      None, alias="forceLoginMethod", examples=["claudeai"]
                                  )
                                  

                                  Use "claudeai" to restrict login to Claude.ai accounts, "console" to restrict login to Claude Console accounts, or "gateway" to restrict login to a cloud gateway. On Claude Code v2.1.212 or later, every first-party login path enforces the restriction, including the VS Code extension, the Agent SDK, claude setup-token, and /install-github-app; before v2.1.212, only terminal logins enforced it. See https://code.claude.com/docs/en/authentication#restrict-login-to-your-organization

                                  force_login_org_uuid class-attribute instance-attribute

                                  force_login_org_uuid: ForceLoginOrgUuid | list[ForceLoginOrgUuidItem] | None = Field(
                                      None, alias="forceLoginOrgUUID", examples=["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"]
                                  )
                                  

                                  Organization UUID to use for OAuth login, or an array of UUIDs to allow several organizations. An empty array fails closed and blocks every login. See https://code.claude.com/docs/en/authentication#restrict-login-to-your-organization

                                  force_remote_settings_refresh class-attribute instance-attribute

                                  force_remote_settings_refresh: bool | None = Field(None, alias='forceRemoteSettingsRefresh')
                                  

                                  (Managed settings only) Block CLI startup until remote managed settings are freshly fetched from the server. If the fetch fails, the CLI exits (fail-closed) rather than continuing with cached settings. When not set, startup continues without waiting for remote settings. See https://code.claude.com/docs/en/server-managed-settings

                                  gcp_auth_refresh class-attribute instance-attribute

                                  gcp_auth_refresh: str | None = Field(
                                      None, alias="gcpAuthRefresh", examples=["gcloud auth application-default login"], min_length=1
                                  )
                                  

                                  Command to run when GCP credentials are expired or cannot be loaded. The command's output is displayed to the user but interactive input is not supported; it times out after three minutes. See https://code.claude.com/docs/en/google-vertex-ai#advanced-credential-configuration

                                  hooks class-attribute instance-attribute

                                  hooks: Hooks | None = Field(
                                      None,
                                      examples=[
                                          {
                                              "PostToolUse": [
                                                  {
                                                      "matcher": "Edit|Write",
                                                      "hooks": [{"type": "command", "command": "prettier --write", "timeout": 5}],
                                                  }
                                              ]
                                          }
                                      ],
                                  )
                                  

                                  Lifecycle event hooks that run at configurable points during Claude Code operation (tool use, session start/end, notifications, prompt submit, message display, and more), not just before/after tool executions. See https://code.claude.com/docs/en/hooks

                                  http_hook_allowed_env_vars class-attribute instance-attribute

                                  http_hook_allowed_env_vars: list[HttpHookAllowedEnvVar] | None = Field(
                                      None, alias="httpHookAllowedEnvVars", examples=[["MY_TOKEN", "HOOK_SECRET"]]
                                  )
                                  

                                  Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration

                                  include_co_authored_by class-attribute instance-attribute

                                  include_co_authored_by: bool | None = Field(True, alias='includeCoAuthoredBy')
                                  

                                  DEPRECATED. Use 'attribution' instead. Whether to include the co-authored-by Claude byline in git commits and pull requests (default: true)

                                  include_git_instructions class-attribute instance-attribute

                                  include_git_instructions: bool | None = Field(True, alias='includeGitInstructions')
                                  

                                  Include built-in git commit and PR workflow instructions in Claude's system prompt. Also configurable via CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS environment variable (set to 1 to disable). See https://code.claude.com/docs/en/settings#available-settings

                                  input_needed_notif_enabled class-attribute instance-attribute

                                  input_needed_notif_enabled: bool | None = Field(False, alias='inputNeededNotifEnabled')
                                  

                                  When Remote Control is connected, send a push notification to your phone when a permission prompt or question is waiting for input. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/settings#available-settings

                                  language class-attribute instance-attribute

                                  language: str | None = Field(None, examples=['japanese', 'spanish', 'french'])
                                  

                                  Configure Claude's preferred response language (e.g., "japanese", "spanish", "french"). Claude will respond in this language by default. Also sets the voice dictation language and terminal tab session title generation. See https://code.claude.com/docs/en/settings#available-settings

                                  managed_mcp_servers class-attribute instance-attribute

                                  managed_mcp_servers: list[dict[str, Any]] | None = Field(None, alias='managedMcpServers')
                                  

                                  (Managed settings, third-party Desktop deployments only) MCP server configurations pushed to all users. Each entry specifies the transport and connection details, plus an optional toolPolicy map. Delivered through the managed settings file or MDM. See https://code.claude.com/docs/en/desktop#enterprise-configuration

                                  minimum_version class-attribute instance-attribute

                                  minimum_version: str | None = Field(None, alias='minimumVersion', examples=['2.1.0'], min_length=1)
                                  

                                  Minimum Claude Code version to stay on. Prevents downgrades when switching release channels. See https://code.claude.com/docs/en/settings#available-settings

                                  model class-attribute instance-attribute

                                  model: str | None = None
                                  

                                  Override the default model used by Claude Code. For finer control, use environment variables: ANTHROPIC_MODEL (runtime override), ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL (per-class pinning), CLAUDE_CODE_SUBAGENT_MODEL (subagent model). See https://code.claude.com/docs/en/model-config

                                  model_overrides class-attribute instance-attribute

                                  model_overrides: dict[str, str] | None = Field(
                                      None,
                                      alias="modelOverrides",
                                      examples=[
                                          {
                                              "claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod"
                                          }
                                      ],
                                  )
                                  

                                  Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs, Vertex AI version names, or Foundry deployment names. Each model picker entry uses its mapped value when calling the provider API. Unknown keys are ignored. See https://code.claude.com/docs/en/model-config#override-model-ids-per-version

                                  otel_headers_helper class-attribute instance-attribute

                                  otel_headers_helper: str | None = Field(None, alias='otelHeadersHelper', min_length=1)
                                  

                                  Path to an executable, or a shell command line with arguments, that outputs OpenTelemetry headers as a JSON object. Runs at startup and re-runs on the interval set by CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS. Requires CLAUDE_CODE_ENABLE_TELEMETRY=1. See https://code.claude.com/docs/en/monitoring-usage#dynamic-headers

                                  output_style class-attribute instance-attribute

                                  output_style: str | None = Field(
                                      None,
                                      alias="outputStyle",
                                      examples=["default", "Proactive", "Explanatory", "Learning"],
                                      min_length=1,
                                  )
                                  

                                  Controls the output style for assistant responses. Built-in styles: default, Proactive, Explanatory, Learning. Custom styles can be added in ~/.claude/output-styles/ or .claude/output-styles/. See https://code.claude.com/docs/en/output-styles

                                  parent_settings_behavior class-attribute instance-attribute

                                  parent_settings_behavior: Literal["first-wins", "merge"] | None = Field(
                                      "first-wins", alias="parentSettingsBehavior"
                                  )
                                  

                                  (Admin/managed settings only) Controls how SDK managedSettings (parent tier) merge with inherited settings. 'first-wins': first non-empty value applies (default). 'merge': merge arrays and objects. See https://code.claude.com/docs/en/server-managed-settings

                                  permission_explainer_enabled class-attribute instance-attribute

                                  permission_explainer_enabled: bool | None = Field(True, alias='permissionExplainerEnabled')
                                  

                                  Show a model-generated explanation of the command when you press Ctrl+E on a Bash or PowerShell permission prompt (default: true). Set to false to turn the shortcut off. See https://code.claude.com/docs/en/permissions#permission-system

                                  permissions class-attribute instance-attribute

                                  permissions: Permissions | None = Field(
                                      None,
                                      examples=[
                                          {
                                              "allow": ["Bash(git add:*)"],
                                              "ask": ["Bash(gh pr create:*)", "Bash(git commit:*)"],
                                              "deny": ["Read(*.env)", "Bash(rm:*)", "Bash(curl:*)"],
                                              "defaultMode": "default",
                                          }
                                      ],
                                  )
                                  

                                  Tool usage permissions configuration. See https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings See https://code.claude.com/docs/en/tools-reference for full list of tools available to Claude.

                                  plans_directory class-attribute instance-attribute

                                  plans_directory: str | None = Field("~/.claude/plans", alias="plansDirectory", examples=["./plans"])
                                  

                                  Customize where plan files are stored. Path is relative to project root (default: ~/.claude/plans)

                                  plugin_configs class-attribute instance-attribute

                                  plugin_configs: dict[str, PluginConfigs] | None = Field(None, alias='pluginConfigs')
                                  

                                  Per-plugin configuration including MCP server user configs and plugin options, keyed by plugin ID (plugin@marketplace format). See https://code.claude.com/docs/en/plugins

                                  plugin_suggestion_marketplaces class-attribute instance-attribute

                                  plugin_suggestion_marketplaces: list[str] | None = Field(None, alias="pluginSuggestionMarketplaces")
                                  

                                  (Managed settings only) Allowlist of marketplace names whose plugins may surface as contextual "suggested for this directory" tips in the /plugin Discover tab. No marketplace-declared suggestions surface without this allowlist. The built-in first-party frontend-design tip is unaffected. See https://code.claude.com/docs/en/settings#available-settings

                                  plugin_trust_message class-attribute instance-attribute

                                  plugin_trust_message: str | None = Field(None, alias='pluginTrustMessage', min_length=1)
                                  

                                  (Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use to provide organization-specific context about approved plugins. See https://code.claude.com/docs/en/settings#plugin-settings

                                  policy_helper class-attribute instance-attribute

                                  policy_helper: PolicyHelper | None = Field(None, alias='policyHelper')
                                  

                                  Admin-deployed executable that computes managed settings dynamically at startup. Honored only from MDM or the system managed-settings.json. Requires Claude Code v2.1.136 or later. See https://code.claude.com/docs/en/settings#available-settings

                                  pr_url_template class-attribute instance-attribute

                                  pr_url_template: str | None = Field(
                                      None,
                                      alias="prUrlTemplate",
                                      examples=["https://reviews.example.com/{owner}/{repo}/pull/{number}"],
                                  )
                                  

                                  URL template for the PR badge shown in the footer and in tool-result summaries. Substitutes placeholders {host}, {owner}, {repo}, {number}, {url} from the gh-reported PR URL. Use this to point PR links at an internal code-review tool instead of github.com. Does not affect #123 autolinks in Claude's prose. See https://code.claude.com/docs/en/settings#available-settings

                                  preferred_notif_channel class-attribute instance-attribute

                                  preferred_notif_channel: (
                                      Literal[
                                          "auto",
                                          "terminal_bell",
                                          "iterm2",
                                          "iterm2_with_bell",
                                          "kitty",
                                          "ghostty",
                                          "notifications_disabled",
                                      ]
                                      | None
                                  ) = Field("auto", alias="preferredNotifChannel")
                                  

                                  Method for task-complete and permission-prompt notifications. "auto" (default) sends a desktop notification in iTerm2, Ghostty, and Kitty and does nothing in other terminals; "terminal_bell" rings the bell in any terminal; "notifications_disabled" turns them off. See https://code.claude.com/docs/en/terminal-config#get-a-terminal-bell-or-notification

                                  prefers_reduced_motion class-attribute instance-attribute

                                  prefers_reduced_motion: bool | None = Field(False, alias='prefersReducedMotion')
                                  

                                  Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility

                                  process_wrapper class-attribute instance-attribute

                                  process_wrapper: str | None = Field(
                                      None, alias="processWrapper", examples=["/opt/corp/launcher --profile claude"]
                                  )
                                  

                                  Corporate launcher command placed in front of the background processes Claude Code starts. Honored from managed settings, a --settings file, and user settings only; the CLAUDE_CODE_PROCESS_WRAPPER environment variable takes precedence when both are set. Requires Claude Code v2.1.210 or later. See https://code.claude.com/docs/en/corporate-launcher

                                  remote_control_at_startup class-attribute instance-attribute

                                  remote_control_at_startup: bool | None = Field(None, alias='remoteControlAtStartup')
                                  

                                  Connect Remote Control automatically when each interactive session starts. true = always, false = never, unset = organization default. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/remote-control#enable-remote-control-for-all-sessions

                                  require_cowork_full_vm_sandbox class-attribute instance-attribute

                                  require_cowork_full_vm_sandbox: bool | None = Field(None, alias='requireCoworkFullVmSandbox')
                                  

                                  (Managed settings only) Run Claude's tools inside an isolated virtual machine instead of on your Mac. Disables the desktop app's iOS Simulator pane and Claude's simulator tools entirely, so the pane cannot attach a device while it is set. See https://code.claude.com/docs/en/desktop-ios-simulator#turn-off-simulator-access

                                  required_maximum_version class-attribute instance-attribute

                                  required_maximum_version: str | None = Field(None, alias='requiredMaximumVersion')
                                  

                                  (Managed settings only) Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup with instructions to install an approved version. See https://code.claude.com/docs/en/admin-setup#decide-what-to-enforce

                                  required_minimum_version class-attribute instance-attribute

                                  required_minimum_version: str | None = Field(None, alias='requiredMinimumVersion')
                                  

                                  (Managed settings only) Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup rather than only warning. See https://code.claude.com/docs/en/admin-setup#decide-what-to-enforce

                                  respect_gitignore class-attribute instance-attribute

                                  respect_gitignore: bool | None = Field(True, alias='respectGitignore')
                                  

                                  Control whether the @ file picker respects .gitignore patterns. When true (default), files matching .gitignore patterns are excluded from suggestions

                                  respond_to_bash_commands class-attribute instance-attribute

                                  respond_to_bash_commands: bool | None = Field(True, alias='respondToBashCommands')
                                  

                                  Whether Claude responds after an input-box ! shell command runs (v2.1.186+). Set to false to add the command output to context without a response. See https://code.claude.com/docs/en/interactive-mode#shell-mode-with--prefix

                                  sandbox class-attribute instance-attribute

                                  sandbox: Sandbox | None = None
                                  

                                  Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing

                                  show_clear_context_on_plan_accept class-attribute instance-attribute

                                  show_clear_context_on_plan_accept: bool | None = Field(False, alias='showClearContextOnPlanAccept')
                                  

                                  When true, the plan-approval dialog offers a "clear context" option. Defaults to false.

                                  show_thinking_summaries class-attribute instance-attribute

                                  show_thinking_summaries: bool | None = Field(False, alias='showThinkingSummaries')
                                  

                                  Show thinking summaries in the transcript view (Ctrl+O). Thinking summaries are not generated by default in interactive sessions; set to true to restore. See https://code.claude.com/docs/en/settings#available-settings

                                  show_turn_duration class-attribute instance-attribute

                                  show_turn_duration: bool | None = Field(True, alias='showTurnDuration')
                                  

                                  Show turn duration messages after responses (e.g., "Cooked for 1m 6s"). Set to false to hide these messages (default: true)

                                  skill_listing_budget_fraction class-attribute instance-attribute

                                  skill_listing_budget_fraction: float | None = Field(
                                      0.01, alias="skillListingBudgetFraction", gt=0.0, le=1.0
                                  )
                                  

                                  Fraction of the model context window reserved for the skill listing sent to Claude (default 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Also configurable via the SLASH_COMMAND_TOOL_CHAR_BUDGET environment variable (fixed character count). See https://code.claude.com/docs/en/skills#skill-descriptions-are-cut-short

                                  skill_listing_max_desc_chars class-attribute instance-attribute

                                  skill_listing_max_desc_chars: int | None = Field(1536, alias='skillListingMaxDescChars', gt=0)
                                  

                                  Per-skill character cap on the combined description and when_to_use text in the skill listing Claude sees each turn. Text longer than this is truncated. See https://code.claude.com/docs/en/skills#skill-descriptions-are-cut-short

                                  skill_overrides class-attribute instance-attribute

                                  skill_overrides: dict[str, Literal["on", "name-only", "user-invocable-only", "off"]] | None = Field(
                                      None, alias="skillOverrides", examples=[{"legacy-context": "name-only", "deploy": "off"}]
                                  )
                                  

                                  Per-skill visibility overrides. Controls whether skills appear to Claude and in the / picker. Values: 'on' (name and description shown, default), 'name-only' (name only), 'user-invocable-only' (hidden from Claude, visible in /), 'off' (hidden everywhere). Plugin skills are not affected by this setting. See https://code.claude.com/docs/en/skills#override-skill-visibility-from-settings

                                  skip_dangerous_mode_permission_prompt class-attribute instance-attribute

                                  skip_dangerous_mode_permission_prompt: bool | None = Field(
                                      None, alias="skipDangerousModePermissionPrompt"
                                  )
                                  

                                  Whether the user has accepted the bypass permissions mode dialog. Typically managed by the CLI rather than set by hand.

                                  skip_web_fetch_preflight class-attribute instance-attribute

                                  skip_web_fetch_preflight: bool | None = Field(None, alias='skipWebFetchPreflight')
                                  

                                  Skip the WebFetch blocklist check for enterprise environments with restrictive security policies. See https://code.claude.com/docs/en/settings#available-settings

                                  skipped_marketplaces class-attribute instance-attribute

                                  skipped_marketplaces: list[SkippedMarketplace] | None = Field(None, alias='skippedMarketplaces')
                                  

                                  List of marketplace names the user has chosen not to install when prompted. See https://code.claude.com/docs/en/discover-plugins

                                  skipped_plugins class-attribute instance-attribute

                                  skipped_plugins: list[SkippedPlugin] | None = Field(None, alias='skippedPlugins')
                                  

                                  List of plugin IDs (plugin@marketplace format) the user has chosen not to install when prompted. See https://code.claude.com/docs/en/discover-plugins

                                  spinner_tips_enabled class-attribute instance-attribute

                                  spinner_tips_enabled: bool | None = Field(True, alias='spinnerTipsEnabled')
                                  

                                  Show tips in the spinner while Claude is working. Set to false to disable tips (default: true)

                                  spinner_tips_override class-attribute instance-attribute

                                  spinner_tips_override: SpinnerTipsOverride | None = Field(None, alias='spinnerTipsOverride')
                                  

                                  Customize the tips displayed in the spinner while Claude is working. See https://code.claude.com/docs/en/settings#available-settings

                                  spinner_verbs class-attribute instance-attribute

                                  spinner_verbs: SpinnerVerbs | None = Field(None, alias='spinnerVerbs')
                                  

                                  Customize the verbs shown in spinner progress messages

                                  ssh_configs class-attribute instance-attribute

                                  ssh_configs: list[SshConfig] | None = Field(None, alias='sshConfigs')
                                  

                                  (Managed settings) Pre-configured SSH connections distributed to Desktop users. See https://code.claude.com/docs/en/desktop#ssh-sessions

                                  ssh_host_allowlist class-attribute instance-attribute

                                  ssh_host_allowlist: list[str] | None = Field(None, alias='sshHostAllowlist')
                                  

                                  (Managed settings only) Allowlist restricting Desktop SSH sessions to approved hosts. Patterns are case-insensitive; * matches any host and *.example.com matches example.com and any subdomain. See https://code.claude.com/docs/en/desktop#ssh-sessions

                                  status_line class-attribute instance-attribute

                                  status_line: StatusLine | None = Field(
                                      None, alias="statusLine", examples=[{"type": "command", "command": "~/.claude/statusline.sh"}]
                                  )
                                  

                                  Custom status line display configuration. See https://code.claude.com/docs/en/statusline

                                  strict_known_marketplaces class-attribute instance-attribute

                                  strict_known_marketplaces: (
                                      list[
                                          StrictMarketplaceHostPattern
                                          | StrictMarketplaceGithub
                                          | StrictMarketplaceGit
                                          | StrictMarketplaceUrl
                                          | StrictMarketplaceNpm
                                          | StrictMarketplaceFile
                                          | StrictMarketplaceDirectory
                                          | StrictMarketplacePathPattern
                                          | StrictMarketplaceSkillsDir
                                      ]
                                      | None
                                  ) = Field(
                                      None,
                                      alias="strictKnownMarketplaces",
                                      examples=[
                                          [
                                              {"source": "github", "repo": "acme-corp/approved-plugins"},
                                              {"source": "npm", "package": "@acme-corp/compliance-plugins"},
                                          ]
                                      ],
                                  )
                                  

                                  (Managed settings only) Allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Uses exact matching for source specifications. See https://code.claude.com/docs/en/plugin-marketplaces#managed-marketplace-restrictions

                                  strict_plugin_only_customization class-attribute instance-attribute

                                  strict_plugin_only_customization: bool | StrictPluginOnlyCustomization | None = Field(
                                      None, alias="strictPluginOnlyCustomization"
                                  )
                                  

                                  (Managed settings) Block non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g., ["skills", "hooks"]); true locks all four; false is an explicit no-op. See https://code.claude.com/docs/en/plugins-reference

                                  subagent_status_line class-attribute instance-attribute

                                  subagent_status_line: SubagentStatusLine | None = Field(None, alias='subagentStatusLine')
                                  

                                  Status line configuration for subagent sessions. See https://code.claude.com/docs/en/statusline#subagent-status-lines

                                  syntax_highlighting_disabled class-attribute instance-attribute

                                  syntax_highlighting_disabled: bool | None = Field(None, alias='syntaxHighlightingDisabled')
                                  

                                  Disable syntax highlighting in diffs, code blocks, and file previews. See https://code.claude.com/docs/en/settings#available-settings

                                  teammate_default_model class-attribute instance-attribute

                                  teammate_default_model: str | None = Field(None, alias='teammateDefaultModel', examples=['sonnet'])
                                  

                                  Default model for agent team teammates when the spawn prompt does not specify one. Set to a model alias such as "sonnet", or null to inherit the lead's current /model selection. Appears in /config as Default teammate model. See https://code.claude.com/docs/en/agent-teams

                                  teammate_mode class-attribute instance-attribute

                                  teammate_mode: Literal["auto", "in-process", "tmux", "iterm2"] | None = Field(
                                      "in-process", alias="teammateMode"
                                  )
                                  

                                  How agent team teammates display: "auto" picks split panes in tmux or iTerm2, in-process otherwise; "iterm2" (added in v2.1.186) forces iTerm2 native split panes and requires the it2 CLI (it shows an error with the install command if it2 is missing). The default is "in-process" (it was "auto" before v2.1.179). Agent teams are experimental and disabled by default. Enable them by adding CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to your settings.json or environment. See https://code.claude.com/docs/en/agent-teams#choose-a-display-mode

                                  terminal_progress_bar_enabled class-attribute instance-attribute

                                  terminal_progress_bar_enabled: bool | None = Field(True, alias='terminalProgressBarEnabled')
                                  

                                  Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: true)

                                  theme class-attribute instance-attribute

                                  theme: (
                                      Literal[
                                          "auto", "dark", "light", "dark-daltonized", "light-daltonized", "dark-ansi", "light-ansi"
                                      ]
                                      | Theme
                                      | None
                                  ) = None
                                  

                                  Color theme for the interface: auto, dark, light, the daltonized variants (deuteranopia-friendly), the ansi variants (16-color terminals), or a custom theme reference such as custom:<slug> or custom:<plugin-name>:<slug>. See https://code.claude.com/docs/en/terminal-config#match-the-color-theme

                                  tui class-attribute instance-attribute

                                  tui: Literal['fullscreen', 'default'] | None = None
                                  

                                  TUI rendering mode. Use "fullscreen" for the flicker-free alt-screen renderer with virtualized scrollback; "default" for the classic main-screen renderer. Corresponds to the /tui command. See https://code.claude.com/docs/en/settings#available-settings

                                  use_auto_mode_during_plan class-attribute instance-attribute

                                  use_auto_mode_during_plan: bool | None = Field(None, alias='useAutoModeDuringPlan')
                                  

                                  When true, apply the auto mode classifier during plan mode to auto-approve safe read-only tool calls while planning. Has no effect unless permissions.defaultMode allows auto. See https://code.claude.com/docs/en/permissions

                                  verbose class-attribute instance-attribute

                                  verbose: bool | None = False
                                  

                                  Show full tool output instead of truncated summaries. The --verbose flag overrides this for a single session. Requires Claude Code v2.1.119 or later. See https://code.claude.com/docs/en/settings#available-settings

                                  view_mode class-attribute instance-attribute

                                  view_mode: Literal['default', 'verbose', 'focus'] | None = Field(None, alias='viewMode')
                                  

                                  Transcript view mode. "default" shows standard interactive view; "verbose" shows expanded tool details; "focus" shows prompt, one-line tool summaries, and final response only (Ctrl+O toggle). See https://code.claude.com/docs/en/settings#available-settings

                                  vim_insert_mode_remaps class-attribute instance-attribute

                                  vim_insert_mode_remaps: dict[str, str] | None = Field(
                                      None, alias="vimInsertModeRemaps", examples=[{"jj": "<Esc>"}]
                                  )
                                  

                                  Map two-key INSERT-mode sequences to Escape in vim editor mode. Each key is exactly two printable characters typed in sequence, and <Esc> is the only supported target; other entries are ignored. Read from user, --settings flag, and managed settings only, so a repository's checked-in settings cannot remap your keystrokes. Has no effect unless editorMode is "vim". Requires Claude Code v2.1.208 or later. See https://code.claude.com/docs/en/interactive-mode#remap-insert-mode-key-sequences

                                  voice class-attribute instance-attribute

                                  voice: Voice | None = None
                                  

                                  Voice dictation settings: enabled turns dictation on, mode selects "hold" or "tap", and autoSubmit sends the prompt on key release in hold mode. Written automatically when you run /voice. Requires a Claude.ai account. See https://code.claude.com/docs/en/voice-dictation

                                  voice_enabled class-attribute instance-attribute

                                  voice_enabled: bool | None = Field(None, alias='voiceEnabled')
                                  

                                  Legacy alias for voice.enabled; prefer the voice object. Requires a Claude.ai account. See https://code.claude.com/docs/en/settings#available-settings

                                  wheel_scroll_acceleration_enabled class-attribute instance-attribute

                                  wheel_scroll_acceleration_enabled: bool | None = Field(None, alias="wheelScrollAccelerationEnabled")
                                  

                                  In fullscreen rendering, accelerate mouse-wheel scroll speed during fast scrolls (v2.1.174+). Set to false for a constant scroll rate per wheel notch. See https://code.claude.com/docs/en/fullscreen#mouse-wheel-scrolling

                                  workflow_keyword_trigger_enabled class-attribute instance-attribute

                                  workflow_keyword_trigger_enabled: bool | None = Field(True, alias='workflowKeywordTriggerEnabled')
                                  

                                  Whether including the keyword "ultracode" in a prompt triggers a dynamic workflow. Requires Claude Code v2.1.157 or later. See https://code.claude.com/docs/en/settings#available-settings

                                  workflow_size_guideline class-attribute instance-attribute

                                  workflow_size_guideline: Literal["unrestricted", "small", "medium", "large"] | None = Field(
                                      "unrestricted", alias="workflowSizeGuideline"
                                  )
                                  

                                  Sets the agent count Claude aims for in the dynamic workflows it writes. Claude Code sends the value to Claude as advice, not an enforced cap. Accepts "unrestricted" (default, which sends no guideline), "small", "medium", or "large". Appears in /config as Dynamic workflow size, and can be set with /config workflowSizeGuideline=small. Requires Claude Code v2.1.202 or later. On v2.1.203 or later the guideline's agent count also replaces the default threshold for the Large workflow warning. See https://code.claude.com/docs/en/workflows#set-a-size-guideline

                                  worktree class-attribute instance-attribute

                                  worktree: Worktree | None = None
                                  

                                  Configuration for --worktree sessions. See https://code.claude.com/docs/en/settings#worktree-settings

                                  wsl_inherits_windows_settings class-attribute instance-attribute

                                  wsl_inherits_windows_settings: bool | None = Field(None, alias='wslInheritsWindowsSettings')
                                  

                                  (Windows managed settings only) When true, Claude Code on WSL reads managed settings from the Windows policy chain in addition to /etc/claude-code, with Windows sources taking priority. Only honored when set in the HKLM registry key or C:\Program Files\ClaudeCode\managed-settings.json, both of which require Windows admin to write. For HKCU policy to also apply on WSL, the flag must additionally be set in HKCU itself. Has no effect on native Windows. See https://code.claude.com/docs/en/settings#available-settings

                                  ClaudeSDKClient

                                  Client for bidirectional, interactive conversations with Claude Code.

                                  Key features: - Bidirectional: Send and receive messages at any time - Stateful: Maintains conversation context across messages - Interactive: Send follow-ups based on responses - Control flow: Support for interrupts and session management

                                  Caveat: As of v0.0.21, you cannot use a ClaudeSDKClient instance across different async runtime contexts (e.g., different trio nurseries or asyncio task groups). The client internally maintains a persistent anyio task group for reading messages that remains active from connect() until disconnect(). This means you must complete all operations with the client within the same async context where it was connected. Ideally, this limitation should not exist.

                                  Source code in src/clawd_code_sdk/client.py
                                   171
                                   172
                                   173
                                   174
                                   175
                                   176
                                   177
                                   178
                                   179
                                   180
                                   181
                                   182
                                   183
                                   184
                                   185
                                   186
                                   187
                                   188
                                   189
                                   190
                                   191
                                   192
                                   193
                                   194
                                   195
                                   196
                                   197
                                   198
                                   199
                                   200
                                   201
                                   202
                                   203
                                   204
                                   205
                                   206
                                   207
                                   208
                                   209
                                   210
                                   211
                                   212
                                   213
                                   214
                                   215
                                   216
                                   217
                                   218
                                   219
                                   220
                                   221
                                   222
                                   223
                                   224
                                   225
                                   226
                                   227
                                   228
                                   229
                                   230
                                   231
                                   232
                                   233
                                   234
                                   235
                                   236
                                   237
                                   238
                                   239
                                   240
                                   241
                                   242
                                   243
                                   244
                                   245
                                   246
                                   247
                                   248
                                   249
                                   250
                                   251
                                   252
                                   253
                                   254
                                   255
                                   256
                                   257
                                   258
                                   259
                                   260
                                   261
                                   262
                                   263
                                   264
                                   265
                                   266
                                   267
                                   268
                                   269
                                   270
                                   271
                                   272
                                   273
                                   274
                                   275
                                   276
                                   277
                                   278
                                   279
                                   280
                                   281
                                   282
                                   283
                                   284
                                   285
                                   286
                                   287
                                   288
                                   289
                                   290
                                   291
                                   292
                                   293
                                   294
                                   295
                                   296
                                   297
                                   298
                                   299
                                   300
                                   301
                                   302
                                   303
                                   304
                                   305
                                   306
                                   307
                                   308
                                   309
                                   310
                                   311
                                   312
                                   313
                                   314
                                   315
                                   316
                                   317
                                   318
                                   319
                                   320
                                   321
                                   322
                                   323
                                   324
                                   325
                                   326
                                   327
                                   328
                                   329
                                   330
                                   331
                                   332
                                   333
                                   334
                                   335
                                   336
                                   337
                                   338
                                   339
                                   340
                                   341
                                   342
                                   343
                                   344
                                   345
                                   346
                                   347
                                   348
                                   349
                                   350
                                   351
                                   352
                                   353
                                   354
                                   355
                                   356
                                   357
                                   358
                                   359
                                   360
                                   361
                                   362
                                   363
                                   364
                                   365
                                   366
                                   367
                                   368
                                   369
                                   370
                                   371
                                   372
                                   373
                                   374
                                   375
                                   376
                                   377
                                   378
                                   379
                                   380
                                   381
                                   382
                                   383
                                   384
                                   385
                                   386
                                   387
                                   388
                                   389
                                   390
                                   391
                                   392
                                   393
                                   394
                                   395
                                   396
                                   397
                                   398
                                   399
                                   400
                                   401
                                   402
                                   403
                                   404
                                   405
                                   406
                                   407
                                   408
                                   409
                                   410
                                   411
                                   412
                                   413
                                   414
                                   415
                                   416
                                   417
                                   418
                                   419
                                   420
                                   421
                                   422
                                   423
                                   424
                                   425
                                   426
                                   427
                                   428
                                   429
                                   430
                                   431
                                   432
                                   433
                                   434
                                   435
                                   436
                                   437
                                   438
                                   439
                                   440
                                   441
                                   442
                                   443
                                   444
                                   445
                                   446
                                   447
                                   448
                                   449
                                   450
                                   451
                                   452
                                   453
                                   454
                                   455
                                   456
                                   457
                                   458
                                   459
                                   460
                                   461
                                   462
                                   463
                                   464
                                   465
                                   466
                                   467
                                   468
                                   469
                                   470
                                   471
                                   472
                                   473
                                   474
                                   475
                                   476
                                   477
                                   478
                                   479
                                   480
                                   481
                                   482
                                   483
                                   484
                                   485
                                   486
                                   487
                                   488
                                   489
                                   490
                                   491
                                   492
                                   493
                                   494
                                   495
                                   496
                                   497
                                   498
                                   499
                                   500
                                   501
                                   502
                                   503
                                   504
                                   505
                                   506
                                   507
                                   508
                                   509
                                   510
                                   511
                                   512
                                   513
                                   514
                                   515
                                   516
                                   517
                                   518
                                   519
                                   520
                                   521
                                   522
                                   523
                                   524
                                   525
                                   526
                                   527
                                   528
                                   529
                                   530
                                   531
                                   532
                                   533
                                   534
                                   535
                                   536
                                   537
                                   538
                                   539
                                   540
                                   541
                                   542
                                   543
                                   544
                                   545
                                   546
                                   547
                                   548
                                   549
                                   550
                                   551
                                   552
                                   553
                                   554
                                   555
                                   556
                                   557
                                   558
                                   559
                                   560
                                   561
                                   562
                                   563
                                   564
                                   565
                                   566
                                   567
                                   568
                                   569
                                   570
                                   571
                                   572
                                   573
                                   574
                                   575
                                   576
                                   577
                                   578
                                   579
                                   580
                                   581
                                   582
                                   583
                                   584
                                   585
                                   586
                                   587
                                   588
                                   589
                                   590
                                   591
                                   592
                                   593
                                   594
                                   595
                                   596
                                   597
                                   598
                                   599
                                   600
                                   601
                                   602
                                   603
                                   604
                                   605
                                   606
                                   607
                                   608
                                   609
                                   610
                                   611
                                   612
                                   613
                                   614
                                   615
                                   616
                                   617
                                   618
                                   619
                                   620
                                   621
                                   622
                                   623
                                   624
                                   625
                                   626
                                   627
                                   628
                                   629
                                   630
                                   631
                                   632
                                   633
                                   634
                                   635
                                   636
                                   637
                                   638
                                   639
                                   640
                                   641
                                   642
                                   643
                                   644
                                   645
                                   646
                                   647
                                   648
                                   649
                                   650
                                   651
                                   652
                                   653
                                   654
                                   655
                                   656
                                   657
                                   658
                                   659
                                   660
                                   661
                                   662
                                   663
                                   664
                                   665
                                   666
                                   667
                                   668
                                   669
                                   670
                                   671
                                   672
                                   673
                                   674
                                   675
                                   676
                                   677
                                   678
                                   679
                                   680
                                   681
                                   682
                                   683
                                   684
                                   685
                                   686
                                   687
                                   688
                                   689
                                   690
                                   691
                                   692
                                   693
                                   694
                                   695
                                   696
                                   697
                                   698
                                   699
                                   700
                                   701
                                   702
                                   703
                                   704
                                   705
                                   706
                                   707
                                   708
                                   709
                                   710
                                   711
                                   712
                                   713
                                   714
                                   715
                                   716
                                   717
                                   718
                                   719
                                   720
                                   721
                                   722
                                   723
                                   724
                                   725
                                   726
                                   727
                                   728
                                   729
                                   730
                                   731
                                   732
                                   733
                                   734
                                   735
                                   736
                                   737
                                   738
                                   739
                                   740
                                   741
                                   742
                                   743
                                   744
                                   745
                                   746
                                   747
                                   748
                                   749
                                   750
                                   751
                                   752
                                   753
                                   754
                                   755
                                   756
                                   757
                                   758
                                   759
                                   760
                                   761
                                   762
                                   763
                                   764
                                   765
                                   766
                                   767
                                   768
                                   769
                                   770
                                   771
                                   772
                                   773
                                   774
                                   775
                                   776
                                   777
                                   778
                                   779
                                   780
                                   781
                                   782
                                   783
                                   784
                                   785
                                   786
                                   787
                                   788
                                   789
                                   790
                                   791
                                   792
                                   793
                                   794
                                   795
                                   796
                                   797
                                   798
                                   799
                                   800
                                   801
                                   802
                                   803
                                   804
                                   805
                                   806
                                   807
                                   808
                                   809
                                   810
                                   811
                                   812
                                   813
                                   814
                                   815
                                   816
                                   817
                                   818
                                   819
                                   820
                                   821
                                   822
                                   823
                                   824
                                   825
                                   826
                                   827
                                   828
                                   829
                                   830
                                   831
                                   832
                                   833
                                   834
                                   835
                                   836
                                   837
                                   838
                                   839
                                   840
                                   841
                                   842
                                   843
                                   844
                                   845
                                   846
                                   847
                                   848
                                   849
                                   850
                                   851
                                   852
                                   853
                                   854
                                   855
                                   856
                                   857
                                   858
                                   859
                                   860
                                   861
                                   862
                                   863
                                   864
                                   865
                                   866
                                   867
                                   868
                                   869
                                   870
                                   871
                                   872
                                   873
                                   874
                                   875
                                   876
                                   877
                                   878
                                   879
                                   880
                                   881
                                   882
                                   883
                                   884
                                   885
                                   886
                                   887
                                   888
                                   889
                                   890
                                   891
                                   892
                                   893
                                   894
                                   895
                                   896
                                   897
                                   898
                                   899
                                   900
                                   901
                                   902
                                   903
                                   904
                                   905
                                   906
                                   907
                                   908
                                   909
                                   910
                                   911
                                   912
                                   913
                                   914
                                   915
                                   916
                                   917
                                   918
                                   919
                                   920
                                   921
                                   922
                                   923
                                   924
                                   925
                                   926
                                   927
                                   928
                                   929
                                   930
                                   931
                                   932
                                   933
                                   934
                                   935
                                   936
                                   937
                                   938
                                   939
                                   940
                                   941
                                   942
                                   943
                                   944
                                   945
                                   946
                                   947
                                   948
                                   949
                                   950
                                   951
                                   952
                                   953
                                   954
                                   955
                                   956
                                   957
                                   958
                                   959
                                   960
                                   961
                                   962
                                   963
                                   964
                                   965
                                   966
                                   967
                                   968
                                   969
                                   970
                                   971
                                   972
                                   973
                                   974
                                   975
                                   976
                                   977
                                   978
                                   979
                                   980
                                   981
                                   982
                                   983
                                   984
                                   985
                                   986
                                   987
                                   988
                                   989
                                   990
                                   991
                                   992
                                   993
                                   994
                                   995
                                   996
                                   997
                                   998
                                   999
                                  1000
                                  1001
                                  1002
                                  1003
                                  1004
                                  1005
                                  1006
                                  1007
                                  1008
                                  1009
                                  1010
                                  1011
                                  1012
                                  1013
                                  1014
                                  1015
                                  1016
                                  1017
                                  1018
                                  1019
                                  1020
                                  1021
                                  1022
                                  1023
                                  1024
                                  1025
                                  1026
                                  1027
                                  1028
                                  1029
                                  1030
                                  1031
                                  1032
                                  1033
                                  1034
                                  1035
                                  1036
                                  1037
                                  1038
                                  1039
                                  1040
                                  1041
                                  1042
                                  1043
                                  1044
                                  1045
                                  1046
                                  1047
                                  1048
                                  1049
                                  1050
                                  1051
                                  1052
                                  1053
                                  1054
                                  1055
                                  1056
                                  1057
                                  1058
                                  1059
                                  1060
                                  1061
                                  1062
                                  1063
                                  1064
                                  1065
                                  1066
                                  1067
                                  1068
                                  1069
                                  1070
                                  1071
                                  1072
                                  1073
                                  1074
                                  1075
                                  1076
                                  1077
                                  1078
                                  1079
                                  1080
                                  1081
                                  1082
                                  1083
                                  1084
                                  1085
                                  1086
                                  1087
                                  1088
                                  1089
                                  1090
                                  1091
                                  1092
                                  1093
                                  1094
                                  1095
                                  1096
                                  1097
                                  1098
                                  1099
                                  1100
                                  1101
                                  1102
                                  1103
                                  1104
                                  1105
                                  1106
                                  1107
                                  1108
                                  class ClaudeSDKClient:
                                      """Client for bidirectional, interactive conversations with Claude Code.
                                  
                                      Key features:
                                      - **Bidirectional**: Send and receive messages at any time
                                      - **Stateful**: Maintains conversation context across messages
                                      - **Interactive**: Send follow-ups based on responses
                                      - **Control flow**: Support for interrupts and session management
                                  
                                      Caveat: As of v0.0.21, you cannot use a ClaudeSDKClient instance across
                                      different async runtime contexts (e.g., different trio nurseries or asyncio
                                      task groups). The client internally maintains a persistent anyio task group
                                      for reading messages that remains active from connect() until disconnect().
                                      This means you must complete all operations with the client within the same
                                      async context where it was connected. Ideally, this limitation should not
                                      exist.
                                      """
                                  
                                      def __init__(
                                          self,
                                          options: ClaudeAgentOptions | None = None,
                                          transport: Transport | None = None,
                                      ) -> None:
                                          """Initialize Claude SDK client."""
                                          options = options or ClaudeAgentOptions()
                                          self.options = options
                                          self._custom_transport = transport
                                          self._query: Query | None = None
                                          self._initialization_result: ClaudeCodeServerInfo | None = None
                                          self.session_usage: Usage = Usage()
                                          self.session_state: SessionState = "idle"
                                          """Cumulative token usage across all queries in this session."""
                                          self.query_usage: Usage = Usage()
                                          """Token usage for the current/last query only (reset on each query() call)."""
                                          self.session_cost: float = 0.0
                                          """Cumulative cost in USD across all queries in this session."""
                                          self.query_cost: float = 0.0
                                          """Cost in USD for the current/last query only (reset on each query() call)."""
                                          self.status: SDKStatus | None = None
                                          """Current client status, or None when idle."""
                                  
                                          self._logfire_prompt: str | None = None
                                          self._cli_version_checked = False
                                  
                                      def _ensure_connected(self) -> Query:
                                          """Return the active Query, raising if not connected."""
                                          if not self._query:
                                              raise CLIConnectionError("Not connected. Call connect() first.")
                                          return self._query
                                  
                                      async def connect(self) -> None:
                                          """Connect to Claude Code CLI and initialize the session."""
                                          # Use provided custom transport or create subprocess transport
                                          warn_if_can_use_tool_shadowed(self.options)
                                          self._query = Query.from_options(self.options, self._custom_transport)
                                          try:
                                              await self._query.transport.connect()
                                              await self._query.start()
                                              await self._initialize()
                                          except BaseException:
                                              # `async with` never reaches __aexit__ when connect() fails: don't leak the
                                              # CLI process and the reader task.
                                              # Shielded: an anyio scope that cancelled connect() stays cancelled.
                                              with anyio.CancelScope(shield=True), contextlib.suppress(Exception):
                                                  await self.disconnect()  # the connect error is the one to see
                                              self._query = None
                                              raise
                                  
                                      async def _initialize(self) -> None:
                                          """Send the initialize control request to the CLI."""
                                          query = self._ensure_connected()
                                          options = self.options
                                          match options.system_prompt, options.include_builtin_system_prompt:
                                              case None, False:
                                                  system_prompt: list[str] | None = [""]  # Clear the builtin prompt
                                                  append_system_prompt: str | None = None
                                              case None, True:
                                                  system_prompt = None  # Use the builtin prompt
                                                  append_system_prompt = None
                                              case str() as prompt_str, True:
                                                  system_prompt = None
                                                  append_system_prompt = prompt_str
                                              case list() as prompt_list, True:
                                                  system_prompt = None
                                                  append_system_prompt = "\n".join(prompt_list)
                                              case str() as prompt_str, False:
                                                  system_prompt = [prompt_str]
                                                  append_system_prompt = None
                                              case list() as prompt_list, False:
                                                  system_prompt = prompt_list
                                                  append_system_prompt = None
                                  
                                          # Calculate initialize timeout
                                          initialize_timeout_ms = int(os.environ.get("CLAUDE_CODE_STREAM_CLOSE_TIMEOUT", "60000"))
                                          initialize_timeout = max(initialize_timeout_ms / 1000.0, 60.0)
                                          match options.get_session():
                                              case NewSession() as s:
                                                  title = s.title
                                              case _:
                                                  title = None
                                          hooks_config = query.build_hooks_config()
                                          capture = options.capture_sdk_mcp_manifests and not os.environ.get(
                                              "CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS"
                                          )
                                          manifests = await query.capture_sdk_mcp_manifests() if capture else None
                                          request = SDKControlInitializeRequest(
                                              hooks=hooks_config,
                                              agents={name: d.to_wire_model() for name, d in (options.agents or {}).items()} or None,
                                              system_prompt=system_prompt,
                                              append_system_prompt=append_system_prompt,
                                              json_schema=options.get_json_schema(),
                                              prompt_suggestions=options.prompt_suggestions,
                                              exclude_dynamic_sections=options.exclude_dynamic_sections,
                                              sdk_mcp_servers=list(query.sdk_mcp_servers.keys()) or None,
                                              sdk_mcp_server_configs=options.sdk_mcp_server_configs(),
                                              sdk_mcp_server_manifests=manifests,
                                              plugins=(plugins := options.initialize_plugins()),
                                              mcp_servers=(mcp_servers := options.initialize_mcp_servers()),
                                              agent_progress_summaries=options.agent_progress_summaries,
                                              title=title,
                                              skills=options.skills,
                                              plan_mode_instructions=options.plan_mode_instructions,
                                              system_prompt_snapshot=options.system_prompt_snapshot,
                                              forward_subagent_text=options.forward_subagent_text or None,
                                              tool_aliases=options.tool_aliases,
                                              per_task_stop_affordance=options.per_task_stop_affordance,
                                          )
                                          response = await query._send_control_request(request, timeout=initialize_timeout)
                                          self._initialization_result = info = ClaudeCodeServerInfo.model_validate(response)
                                          # CLIs that predate the field: checked on the first system/init message instead
                                          if info.claude_code_version is not None:
                                              check_claude_version(info.claude_code_version)
                                              self._cli_version_checked = True
                                          if mcp_servers is not None and info.mcp_servers_applied is not True:
                                              # Absent on CLIs that predate the field: they never read `mcpServers`
                                              raise CLIConnectionError(
                                                  "Claude Code did not take the MCP servers sent in the initialize request. "
                                                  'Update Claude Code (2.1.261 or newer) or set mcp_servers_delivery="argv".'
                                              )
                                          if plugins is not None and info.plugins_applied is not True:
                                              raise CLIConnectionError(
                                                  "Claude Code did not load the plugins sent in the initialize request. "
                                                  'Update Claude Code or set plugin_delivery="argv".'
                                              )
                                          blocks_on_failure = any(
                                              m.on_failure not in (None, "continue")
                                              for matchers in (options.hooks or {}).values()
                                              for m in matchers
                                          )
                                          if blocks_on_failure:
                                              if not info.hook_on_failure_supported:
                                                  raise CLIConnectionError(
                                                      "The process answering initialize does not honor on_failure on hook "
                                                      "matchers, so a failing hook would not block. "
                                                      'Update Claude Code or remove on_failure="block".'
                                                  )
                                              if info.hooks_applied is False:
                                                  raise CLIConnectionError(
                                                      "This session was already running and did not register your hooks, "
                                                      'so a hook set to on_failure="block" would never run.'
                                                  )
                                  
                                      async def receive_messages(self) -> AsyncIterator[Message]:
                                          """Receive all messages from Claude."""
                                          query = self._ensure_connected()
                                          async for data in query.receive_messages():
                                              try:
                                                  message = parse_message(data)
                                              except MessageParseError:
                                                  # A newer CLI may send message types this SDK does not model yet: skip
                                                  # them unless CLAWD_STRICT_MESSAGES is set. Malformed known types raise.
                                                  if (kind := unknown_message_kind(data)) is None or strict_messages():
                                                      raise
                                                  if kind not in _warned_unknown_kinds:
                                                      _warned_unknown_kinds.add(kind)
                                                      logger.warning(
                                                          "Skipping unknown Claude Code message type %r (set %s=1 to raise)",
                                                          kind,
                                                          STRICT_MESSAGES_ENV,
                                                      )
                                                  continue
                                              match message:
                                                  case AssistantMessage():
                                                      message.raise_if_api_error()
                                                  case StatusSystemMessage(status=status):
                                                      self.status = status
                                                  case InitSystemMessage(claude_code_version=version) if (
                                                      not self._cli_version_checked
                                                  ):
                                                      check_claude_version(version)
                                                      self._cli_version_checked = True
                                                  case SessionStateChangedMessage(state=state):
                                                      self.session_state = state
                                                  case (
                                                      ResultSuccessMessage(usage=usage, total_cost_usd=total_cost)
                                                      | ResultErrorMessage(usage=usage, total_cost_usd=total_cost)
                                                  ):
                                                      self.query_usage.accumulate(usage)
                                                      self.session_usage.accumulate(usage)
                                                      # total_cost_usd is cumulative; a query adds the delta of each of its
                                                      # results (a steered query has one per cycle)
                                                      self.query_cost += total_cost - self.session_cost
                                                      self.session_cost = total_cost
                                              yield message
                                  
                                      async def query(
                                          self,
                                          *prompts: str | UserPrompt,
                                          session_id: str = "default",
                                          parent_tool_use_id: str | None = None,
                                          should_query: bool = True,
                                          priority: MessagePriority | None = None,
                                          uuid: str | None = None,
                                      ) -> None:
                                          """Send a new user message with one or more content blocks.
                                  
                                          Starts a new query: ``query_usage`` and ``query_cost`` count from here.
                                  
                                          Args:
                                              *prompts: One or more content blocks. Strings are converted to
                                                  UserTextPrompt automatically. Pass multiple to combine, e.g.
                                                  ``query(image_prompt, "What's in this image?")``.
                                              session_id: Session identifier for the message.
                                              parent_tool_use_id: If responding to a tool use, the tool_use block ID.
                                              should_query: Whether to query the model for a response. Defaults to True.
                                              priority: The priority of the message. Defaults to None.
                                              uuid: ID of the message; the CLI then reports its progress as
                                                  ``CommandLifecycleMessage`` frames and names it in results.
                                          """
                                          prompt = prompts[0] if prompts else None
                                          self._logfire_prompt = str(prompt)
                                          self.query_usage.reset()
                                          self.query_cost = 0.0
                                          await self._send_user_message(
                                              prompts,
                                              session_id=session_id,
                                              parent_tool_use_id=parent_tool_use_id,
                                              should_query=should_query,
                                              priority=priority,
                                              uuid=uuid,
                                          )
                                  
                                      async def steer(
                                          self,
                                          *prompts: str | UserPrompt,
                                          priority: MessagePriority = "now",
                                          session_id: str = "default",
                                      ) -> str:
                                          """Send a user message into the running query instead of starting a new one.
                                  
                                          ``query_usage`` and ``query_cost`` keep counting the running query. With
                                          ``"now"`` the CLI takes the message in at once: it ends the cycle that is
                                          generating (which reports a result of its own) or moves a running foreground
                                          tool to the background, and works on the message in the same query. ``"later"``
                                          waits for the running cycle (e.g. while a permission request is open).
                                  
                                          Args:
                                              *prompts: Content blocks of the message (strings become text blocks).
                                              priority: When the CLI takes the message in.
                                              session_id: Session identifier for the message.
                                  
                                          Returns:
                                              The message's uuid, which ``CommandLifecycleMessage.command_uuid`` and the
                                              results' ``user_message_uuids`` refer to.
                                          """
                                          message_uuid = str(uuid4())
                                          await self._send_user_message(
                                              prompts, session_id=session_id, priority=priority, uuid=message_uuid
                                          )
                                          return message_uuid
                                  
                                      async def _send_user_message(
                                          self,
                                          prompts: tuple[str | UserPrompt, ...],
                                          *,
                                          session_id: str,
                                          parent_tool_use_id: str | None = None,
                                          should_query: bool = True,
                                          priority: MessagePriority | None = None,
                                          uuid: str | None = None,
                                      ) -> None:
                                          self._ensure_connected()
                                          if not self._query:
                                              raise CLIConnectionError("Not connected. Call connect() first.")
                                          if not prompts:
                                              raise ValueError("At least one prompt is required")
                                          # Collect content blocks
                                          blocks = [UserTextPrompt(text=p) if isinstance(p, str) else p for p in prompts]
                                          # message_content = [b.to_content_block() for b in blocks]
                                          # wire_message = UserMessage(
                                          #     parent_tool_use_id=parent_tool_use_id,
                                          #     session_id=session_id,
                                          #     message=MessageParam(content=message_content),
                                          # )
                                          message_content = [cast(dict[str, Any], b.to_content_block()) for b in blocks]
                                          wire_message = {
                                              "type": "user",
                                              "message": {"role": "user", "content": message_content},
                                              "parent_tool_use_id": parent_tool_use_id,
                                              "session_id": session_id,
                                              "shouldQuery": should_query,
                                              "priority": priority,
                                          }
                                          if uuid is not None:
                                              wire_message["uuid"] = uuid
                                          if self.options.verbatim_prompts:
                                              wire_message["client_composed"] = True
                                          await self._query.write_json(wire_message)
                                  
                                      async def interrupt(self, *, cancel_queued: bool = False) -> SDKControlInterruptResponse | None:
                                          """Send interrupt signal (only works with streaming mode).
                                  
                                          Args:
                                              cancel_queued: Also cancel queued (not yet started) user messages.
                                  
                                          Returns:
                                              Which queued messages are still queued / were cancelled
                                              (None on CLIs that don't report it).
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlInterruptRequest(cancel_queued=cancel_queued or None)
                                          result = await query._send_control_request(request)
                                          return SDKControlInterruptResponse.model_validate(result) if result else None
                                  
                                      async def set_permission_mode(
                                          self, mode: PermissionMode
                                      ) -> SDKControlSetPermissionModeResponse | None:
                                          """Change permission mode during conversation (only works with streaming mode).
                                  
                                          Args:
                                              mode: The permission mode to set. Valid options:
                                                  - 'default': CLI prompts for dangerous tools
                                                  - 'acceptEdits': Auto-accept file edits
                                                  - 'plan': Plan mode for planning tasks
                                                  - 'bypassPermissions': Allow all tools (use with caution)
                                  
                                          Returns:
                                              The mode now in effect (it can differ from ``mode``), or None if the
                                              CLI answered without a payload (before Claude Code 2.1.332).
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlSetPermissionModeRequest(mode=mode)
                                          result = await query._send_control_request(request)
                                          return SDKControlSetPermissionModeResponse.model_validate(result) if result else None
                                  
                                      async def set_model(self, model: str | None = None) -> None:
                                          """Change the AI model during conversation (only works with streaming mode).
                                  
                                          Args:
                                              model: The model to use, or None to use default. Example: 'claude-sonnet-4-5'
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlSetModelRequest(model=model)
                                          await query._send_control_request(request)
                                  
                                      async def cancel_async_message(self, message_uuid: str) -> None:
                                          """Drop a pending async user message from the command queue by uuid."""
                                          query = self._ensure_connected()
                                          request = SDKControlCancelAsyncMessageRequest(message_uuid=message_uuid)
                                          await query._send_control_request(request)
                                  
                                      async def stop_task(self, task_id: str) -> None:
                                          """Stop a running task."""
                                          query = self._ensure_connected()
                                          request = SDKControlStopTaskRequest(task_id=task_id)
                                          await query._send_control_request(request)
                                  
                                      async def rewind_files(self, user_message_id: str) -> None:
                                          """Rewind tracked files to their state at a specific user message.
                                  
                                          Requires:
                                              - `enable_file_checkpointing=True` to track file changes
                                              - `extra_args={"replay-user-messages": None}` to receive UserMessage
                                                objects with `uuid` in the response stream
                                  
                                          Args:
                                              user_message_id: UUID of the user message to rewind to. This should be
                                                  the `uuid` field from a `UserMessage` received during the conversation.
                                  
                                          Example:
                                              ```python
                                              options = ClaudeAgentOptions(
                                                  enable_file_checkpointing=True,
                                                  extra_args={"replay-user-messages": None},
                                              )
                                              async with ClaudeSDKClient(options) as client:
                                                  await client.query("Make some changes to my files")
                                                  async for msg in client.receive_response():
                                                      if isinstance(msg, UserMessage) and msg.uuid:
                                                          checkpoint_id = msg.uuid  # Save this for later
                                  
                                                  # Later, rewind to that point
                                                  await client.rewind_files(checkpoint_id)
                                              ```
                                          """
                                          query = self._ensure_connected()
                                          req = SDKControlRewindFilesRequest(user_message_id=user_message_id)
                                          await query._send_control_request(req)
                                  
                                      async def seed_read_state(self, path: str, mtime: int) -> None:
                                          """Seed the CLI's readFileState cache with a path+mtime entry.
                                  
                                          Use when the client observed a Read that has since been removed from context
                                          (e.g. by snip), so a subsequent Edit won't fail "file not read yet".
                                          If the file changed on disk since the given mtime, the seed is skipped
                                          and Edit will correctly require a fresh Read.
                                  
                                          Args:
                                              path: Path to the file that was previously Read
                                              mtime: File mtime (floored ms) at the time of the observed Read
                                          """
                                          query = self._ensure_connected()
                                          req = SDKControlSeedReadStateRequest(path=path, mtime=mtime)
                                          await query._send_control_request(req)
                                  
                                      async def get_mcp_status(self) -> list[McpServerStatusEntry]:
                                          """Get current MCP server connection status.
                                  
                                          Returns:
                                              Validated MCP status response containing server statuses,
                                              configurations, tools, and connection information.
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlMcpStatusRequest()
                                          result = await query._send_control_request(request)
                                          response = McpStatusResponse.model_validate(result)
                                          return response.mcp_servers
                                  
                                      async def set_mcp_servers(
                                          self, servers: dict[str, ExternalMcpServerConfig]
                                      ) -> McpSetServersResult:
                                          """Add, replace, or remove MCP servers dynamically mid-session.
                                  
                                          Allows dynamic registration of MCP servers without restarting the session.
                                          Pass an empty dict to remove all dynamic servers.
                                  
                                          The server name is automatically injected from the dict key into each
                                          config, so callers don't need to specify it redundantly.
                                  
                                          Args:
                                              servers: Dictionary mapping server names to server configurations.
                                                  Values are typed MCP server configs (McpStdioServerConfig,
                                                  McpSSEServerConfig, McpHttpServerConfig, or McpSdkServerConfig).
                                  
                                          Returns:
                                              Dictionary with results:
                                              - 'added': List of server names that were added
                                              - 'removed': List of server names that were removed
                                              - 'errors': Dict mapping server names to error messages (if any)
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlMcpSetServersRequest(servers=servers)
                                          result = await query._send_control_request(request)
                                          return McpSetServersResult.model_validate(result)
                                  
                                      async def mcp_reconnect(self, server_name: str) -> None:
                                          """Reconnect to an MCP server."""
                                          query = self._ensure_connected()
                                          request = SDKControlMcpReconnectRequest(server_name=server_name)
                                          await query._send_control_request(request)
                                  
                                      async def mcp_toggle(self, server_name: str, *, enabled: bool) -> None:
                                          """Enable or disable an MCP server."""
                                          query = self._ensure_connected()
                                          request = SDKControlMcpToggleRequest(server_name=server_name, enabled=enabled)
                                          await query._send_control_request(request)
                                  
                                      async def generate_session_title(
                                          self, description: str, *, persist: bool = False, timeout: float | None = 120.0
                                      ) -> str | None:
                                          """Generate a session title from ``description`` with the CLI's title model.
                                  
                                          Args:
                                              description: Text to title (the CLI reads its trailing ~1000 characters).
                                              persist: Store it as the current session's title; a session that has a title
                                                  already returns that one.
                                              timeout: Seconds to wait for the model (None: no limit).
                                  
                                          Returns:
                                              The title, or None when the text is too short to title.
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlGenerateSessionTitleRequest(description=description, persist=persist)
                                          result = await query._send_control_request(request, timeout=timeout)
                                          title = (result or {}).get("title")
                                          return title if isinstance(title, str) and title else None
                                  
                                      async def end_session(self) -> None:
                                          """End the current session."""
                                          query = self._ensure_connected()
                                          request = SDKControlEndSessionRequest()
                                          await query._send_control_request(request)
                                  
                                      async def remote_control(self, *, enabled: bool) -> RemoteControlResponse | None:
                                          """Toggle the remote control REPL bridge for external session access.
                                  
                                          When enabled, starts a bridge that allows remote clients to send prompts,
                                          permission responses, interrupts, and model changes into the session.
                                  
                                          Returns:
                                              A ``RemoteControlResponse`` with session URLs and environment ID
                                              when enabling, or ``None`` when disabling.
                                          """
                                          query = self._ensure_connected()
                                          req = SDKControlRemoteControlRequest(enabled=enabled)
                                          result = await query._send_control_request(req)
                                          if not result:
                                              return None
                                          return RemoteControlResponse.model_validate(result)
                                  
                                      async def apply_flag_settings(self, settings: ClaudeCodeSettings) -> None:
                                          """Apply runtime settings overrides without restarting the session.
                                  
                                          Flag settings are an in-memory settings source that gets merged with
                                          other sources (user, project, etc.) to produce the effective settings.
                                  
                                          Args:
                                              settings: Settings to apply. Only fields that were set explicitly (and are
                                                  not None) are sent: defaults would override every other settings source.
                                          """
                                          query = self._ensure_connected()
                                          serialized = settings.model_dump(by_alias=True, exclude_unset=True, exclude_none=True)
                                          req = SDKControlApplyFlagSettingsRequest(settings=serialized)
                                          await query._send_control_request(req)
                                  
                                      async def get_settings(self) -> GetSettingsResponse:
                                          """Get the effective merged settings and raw per-source settings."""
                                          query = self._ensure_connected()
                                          request = SDKControlGetSettingsRequest()
                                          result = await query._send_control_request(request)
                                          return GetSettingsResponse.model_validate(result)
                                  
                                      async def get_context_usage(
                                          self, detail: Literal["summary", "full"] | None = None
                                      ) -> SDKControlGetContextUsageResponse:
                                          """Get a breakdown of current context window usage by category."""
                                          query = self._ensure_connected()
                                          request = SDKControlGetContextUsageRequest(detail=detail)
                                          result = await query._send_control_request(request)
                                          return SDKControlGetContextUsageResponse.model_validate(result)
                                  
                                      # async def get_session_cost(self) -> SDKControlGetSessionCostResponse:
                                      #     """Get the formatted session cost summary (the same text as /usage)."""
                                      #     query = self._ensure_connected()
                                      #     request = SDKControlGetSessionCostRequest()
                                      #     result = await query._send_control_request(request)
                                      #     return SDKControlGetSessionCostResponse.model_validate(result)
                                  
                                      async def mcp_authenticate(self, server_name: str) -> McpAuthenticateResponse:
                                          """Trigger OAuth authentication for an MCP server.
                                  
                                          Returns:
                                              Response indicating whether user action is required and the auth URL if so.
                                          """
                                          query = self._ensure_connected()
                                          req = SDKControlMcpAuthenticateRequest(server_name=server_name)
                                          result = await query._send_control_request(req)
                                          return McpAuthenticateResponse.model_validate(result)
                                  
                                      async def mcp_clear_auth(self, server_name: str) -> None:
                                          """Clear OAuth credentials for an MCP server."""
                                          query = self._ensure_connected()
                                          req = SDKControlMcpClearAuthRequest(server_name=server_name)
                                          await query._send_control_request(req)
                                  
                                      async def mcp_oauth_callback_url(self, server_name: str, callback_url: str) -> None:
                                          """Provide an OAuth redirect callback URL to complete an MCP server OAuth flow.
                                  
                                          After the user completes browser-based OAuth, call this with the full
                                          redirect URL (containing the authorization code) to finish the flow.
                                          """
                                          query = self._ensure_connected()
                                          req = SDKControlMcpOAuthCallbackUrlRequest(
                                              server_name=server_name, callback_url=callback_url
                                          )
                                          await query._send_control_request(req)
                                  
                                      async def claude_oauth_wait_for_completion(
                                          self, *, timeout: float | None = None
                                      ) -> ClaudeOAuthWaitForCompletionResponse:
                                          """Wait for an in-progress Claude OAuth flow to complete.
                                  
                                          Args:
                                              timeout: Seconds to wait for the user to finish the browser login
                                                  (None, the default: no limit).
                                  
                                          Returns:
                                              Account details (email, organization, subscriptionType, etc.).
                                          """
                                          query = self._ensure_connected()
                                          req = SDKControlClaudeOAuthWaitForCompletionRequest()
                                          data = await query._send_control_request(req, timeout=timeout)
                                          return ClaudeOAuthWaitForCompletionResponse.model_validate(data)
                                  
                                      async def side_question(
                                          self, question: str, *, timeout: float | None = 600.0
                                      ) -> SideQuestionResponse:
                                          """Send a side question to the model using the current conversation context.
                                  
                                          The model answers the question without it being added to the main
                                          conversation history.
                                  
                                          Args:
                                              question: The question to ask the model.
                                              timeout: Seconds to wait for the answer (None: no limit).
                                  
                                          Returns:
                                              The model's answer, or None if no context was available.
                                          """
                                          query = self._ensure_connected()
                                          req = SDKControlSideQuestionRequest(question=question)
                                          data = await query._send_control_request(req, timeout=timeout)
                                          return SideQuestionResponse.model_validate(data)
                                  
                                      async def channel_enable(self, server_name: str) -> None:
                                          """Enable MCP channel notifications for a marketplace plugin server."""
                                          query = self._ensure_connected()
                                          req = SDKControlChannelEnableRequest(server_name=server_name)
                                          await query._send_control_request(req)
                                  
                                      async def set_max_thinking_tokens(
                                          self,
                                          max_thinking_tokens: int | None,
                                          thinking_display: Literal["summarized", "omitted", "highlights"] | None = None,
                                      ) -> None:
                                          """Set the maximum number of thinking tokens (and optionally the display mode)."""
                                          query = self._ensure_connected()
                                          request = SDKControlSetMaxThinkingTokensRequest(
                                              max_thinking_tokens=max_thinking_tokens, thinking_display=thinking_display
                                          )
                                          await query._send_control_request(request)
                                  
                                      async def background_tasks(self, tool_use_id: str | None = None) -> bool:
                                          """Move running foreground tasks (or a single tool use) to the background.
                                  
                                          Returns:
                                              Whether anything was backgrounded.
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlBackgroundTasksRequest(tool_use_id=tool_use_id)
                                          result = await query._send_control_request(request)
                                          return bool((result or {}).get("backgrounded", True))
                                  
                                      async def get_task_output(self, task_id: str) -> SDKControlGetTaskOutputResponse:
                                          """Read the output collected so far for a background task."""
                                          query = self._ensure_connected()
                                          request = SDKControlGetTaskOutputRequest(task_id=task_id)
                                          result = await query._send_control_request(request)
                                          return SDKControlGetTaskOutputResponse.model_validate(result)
                                  
                                      async def get_usage(self, *, skip_behaviors: bool = True) -> SDKControlGetUsageResponse:
                                          """Get session usage and plan rate-limit windows (experimental, shape may change).
                                  
                                          Args:
                                              skip_behaviors: Skip the (slow) scan of local transcripts that fills
                                                  ``behaviors``.
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlGetUsageRequest(skip_behaviors=skip_behaviors or None)
                                          result = await query._send_control_request(request)
                                          return SDKControlGetUsageResponse.model_validate(result)
                                  
                                      async def get_binary_version(self) -> dict[str, Any]:
                                          """Get version info of the running Claude Code binary."""
                                          query = self._ensure_connected()
                                          return await query._send_control_request(SDKControlGetBinaryVersionRequest())
                                  
                                      async def list_models(self) -> list[ClaudeCodeModelInfo]:
                                          """Fetch the list of available models from the CLI."""
                                          query = self._ensure_connected()
                                          result = await query._send_control_request(SDKControlListModelsRequest())
                                          return [ClaudeCodeModelInfo.model_validate(m) for m in (result or {}).get("models", [])]
                                  
                                      async def reload_skills(self) -> list[ClaudeCodeCommandInfo]:
                                          """Re-scan skills from disk and return the refreshed skill list."""
                                          query = self._ensure_connected()
                                          result = await query._send_control_request(SDKControlReloadSkillsRequest())
                                          return SDKControlReloadSkillsResponse.model_validate(result).skills
                                  
                                      async def reload_output_styles(self) -> list[str]:
                                          """Re-scan output styles from disk and return the available style names."""
                                          query = self._ensure_connected()
                                          result = await query._send_control_request(SDKControlReloadOutputStylesRequest())
                                          return SDKControlReloadOutputStylesResponse.model_validate(result).available_output_styles
                                  
                                      async def read_mcp_resource(
                                          self, server_name: str, uri: str
                                      ) -> SDKControlMcpReadResourceResponse:
                                          """Read a resource from a connected MCP server."""
                                          query = self._ensure_connected()
                                          request = SDKControlMcpReadResourceRequest(server_name=server_name, uri=uri)
                                          result = await query._send_control_request(request)
                                          return SDKControlMcpReadResourceResponse.model_validate(result)
                                  
                                      async def update_settings(
                                          self,
                                          source: Literal["localSettings", "userSettings"],
                                          settings: dict[str, Any],
                                      ) -> None:
                                          """Persist settings to the local or user settings file."""
                                          query = self._ensure_connected()
                                          request = SDKControlUpdateSettingsRequest(source=source, settings=settings)
                                          await query._send_control_request(request)
                                  
                                      async def list_permission_rules(self) -> dict[str, Any]:
                                          """List the effective permission rules (raw ``state`` payload)."""
                                          query = self._ensure_connected()
                                          result = await query._send_control_request(SDKControlListPermissionRulesRequest())
                                          state: dict[str, Any] = (result or {}).get("state", {})
                                          return state
                                  
                                      async def register_repo_root(
                                          self,
                                          directory: str | Path,
                                          *,
                                          reload_claude_md: bool | None = None,
                                          reload_plugins: bool | None = None,
                                          reload_skills: bool | None = None,
                                      ) -> None:
                                          """Register an additional repository root for the session (like /add-dir)."""
                                          query = self._ensure_connected()
                                          request = SDKControlRegisterRepoRootRequest(
                                              directory=str(directory),
                                              reload_claude_md=reload_claude_md,
                                              reload_plugins=reload_plugins,
                                              reload_skills=reload_skills,
                                          )
                                          await query._send_control_request(request)
                                  
                                      async def get_hooks_listing(self) -> dict[str, Any]:
                                          """Get the listing of configured hooks (same data as /hooks)."""
                                          query = self._ensure_connected()
                                          return await query._send_control_request(SDKControlGetHooksListingRequest())
                                  
                                      async def supported_agents(self) -> list[ClaudeCodeAgentInfo]:
                                          """Get the list of available subagents for the current session.
                                  
                                          Returns:
                                              List of available agents with their names, descriptions, and configuration.
                                          """
                                          if self._initialization_result is None:
                                              raise RuntimeError("Not initialized. Call connect() first.")
                                          return self._initialization_result.agents
                                  
                                      async def get_file(self, path: str, max_bytes: int | None = None) -> SDKControlReadFileResponse:
                                          """Get the contents of a file from the server.
                                  
                                          Args:
                                              path: Path to the file to read
                                              max_bytes: Maximum number of bytes to read (default: None, no limit)
                                  
                                          Returns:
                                              The file contents and metadata
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlReadFileRequest(path=path, max_bytes=max_bytes)
                                          result = await query._send_control_request(request)
                                          return SDKControlReadFileResponse.model_validate(result)
                                  
                                      async def call_tool(
                                          self,
                                          tool: str,
                                          arguments: dict[str, Any] | None = None,
                                          *,
                                          timeout: float | None = 600.0,
                                      ) -> Any:
                                          """Call a tool on the server.
                                  
                                          Args:
                                              tool: The name of the tool to call
                                              arguments: Optional dictionary of arguments for the tool
                                              timeout: Seconds to wait for the tool's result (None: no limit)
                                  
                                          Returns:
                                              The result of the tool call
                                          """
                                          query = self._ensure_connected()
                                          request = SDKControlMcpCallRequest(tool=tool, arguments=arguments)
                                          return await query._send_control_request(request, timeout=timeout)
                                  
                                      async def get_server_info(self) -> ClaudeCodeServerInfo | None:
                                          """Get server initialization info including available commands and output styles.
                                  
                                          Returns initialization information from the Claude Code server including:
                                          - Available commands (slash commands, system commands, etc.)
                                          - Current and available output styles
                                          - Server capabilities
                                  
                                          Returns:
                                              Parsed server info, or None if not yet initialized
                                          """
                                          return self._initialization_result
                                  
                                      async def receive_response_instrumented(self) -> AsyncIterator[Message]:
                                          from logfire import Logfire
                                          from logfire._internal.integrations.llm_providers.semconv import (
                                              INPUT_MESSAGES,
                                              OPERATION_NAME,
                                              PROVIDER_NAME,
                                              REQUEST_MODEL,
                                              RESPONSE_MODEL,
                                              SYSTEM,
                                              SYSTEM_INSTRUCTIONS,
                                              ChatMessage,
                                              TextPart,
                                          )
                                          from logfire._internal.utils import handle_internal_errors
                                  
                                          from clawd_code_sdk.instrumentation import ConversationState, record_result
                                          from clawd_code_sdk.models.content_blocks import ToolResultBlock, ToolUseBlock
                                  
                                          logfire_instance = Logfire()
                                          logfire_claude = logfire_instance.with_settings(custom_scope_suffix="clawd_code_sdk")
                                  
                                          input_messages: list[ChatMessage] = []
                                          if prompt := self._logfire_prompt:
                                              part = TextPart(type="text", content=prompt)
                                              input_messages = [ChatMessage(role="user", parts=[part])]
                                  
                                          span_data: dict[str, Any] = {
                                              OPERATION_NAME: "invoke_agent",
                                              PROVIDER_NAME: "anthropic",
                                              SYSTEM: "anthropic",
                                          }
                                          if input_messages:
                                              span_data[INPUT_MESSAGES] = input_messages
                                          if self.options and (system_prompt := self.options.system_prompt):
                                              text = str(system_prompt)
                                              span_data[SYSTEM_INSTRUCTIONS] = [TextPart(type="text", content=text)]
                                  
                                          with logfire_claude.span("invoke_agent", **span_data) as root_span:
                                              state = ConversationState(
                                                  logfire=logfire_claude,
                                                  root_span=root_span,
                                                  input_messages=input_messages,
                                                  system_instructions=span_data.get(SYSTEM_INSTRUCTIONS),
                                              )
                                              # Open the first chat span now — the LLM call starts at query time.
                                              state.open_chat_span()
                                  
                                              try:
                                                  async for msg in self.receive_response():
                                                      with handle_internal_errors:  # ty:ignore[invalid-context-manager]
                                                          match msg:
                                                              case AssistantMessage():
                                                                  state.handle_assistant_message(msg)
                                                                  # Open tool spans for any tool_use blocks.
                                                                  tool_blocks = [
                                                                      b for b in msg.content if isinstance(b, ToolUseBlock)
                                                                  ]
                                                                  state.open_tool_spans(tool_blocks)
                                                              case UserMessage():
                                                                  # Close tool spans from tool results before
                                                                  # opening the next chat span.
                                                                  content = msg.message.content
                                                                  if isinstance(content, (list, tuple)):
                                                                      result_blocks = [
                                                                          b for b in content if isinstance(b, ToolResultBlock)
                                                                      ]
                                                                      state.close_tool_spans(result_blocks)
                                                                  state.handle_user_message()
                                                              case ResultSuccessMessage() | ResultErrorMessage():
                                                                  record_result(root_span, msg)
                                                                  if state.model:
                                                                      root_span.set_attribute(REQUEST_MODEL, state.model)
                                                                      root_span.set_attribute(RESPONSE_MODEL, state.model)
                                                              case _:
                                                                  pass
                                                      yield msg
                                              finally:
                                                  state.close()
                                  
                                      async def receive_response(self) -> AsyncIterator[Message]:
                                          """Receive messages from Claude until the response is complete.
                                  
                                          This async iterator yields all messages in sequence and automatically
                                          terminates when the session transitions to ``idle`` state — the
                                          authoritative signal that the CLI has fully finished its turn
                                          (held-back results flushed, background agent loops exited).
                                  
                                          **Stopping Behavior:**
                                          - Yields each message as it's received
                                          - Terminates after yielding a ``SessionStateChangedMessage`` with
                                            ``state='idle'``
                                          - The final message in the collected list will always be the idle
                                            state-change message
                                  
                                          Yields:
                                              Message: Each message received
                                  
                                          Note:
                                              To collect all messages: `messages = [msg async for msg in client.receive_response()]`
                                          """
                                          async for message in self.receive_messages():
                                              yield message
                                              if isinstance(message, SessionStateChangedMessage) and message.state == "idle":
                                                  return
                                  
                                      async def disconnect(self) -> None:
                                          """Disconnect from Claude."""
                                          if self._query:
                                              await self._query.close()
                                              self._query = None
                                  
                                      @classmethod
                                      async def one_shot(
                                          cls,
                                          *prompts: str | UserPrompt,
                                          options: ClaudeAgentOptions | None = None,
                                          transport: Transport | None = None,
                                      ) -> AsyncIterator[Message]:
                                          """One-shot query convenience method.
                                  
                                          Args:
                                              *prompts: One or more content blocks to send.
                                              options: Optional configuration.
                                              transport: Optional transport implementation override.
                                  
                                          Yields:
                                              Messages from the conversation
                                          """
                                          client = cls(options=options, transport=transport)
                                          try:
                                              await client.connect()
                                              await client.query(*prompts)
                                              async for message in client.receive_response():
                                                  yield message
                                          finally:
                                              await client.disconnect()
                                  
                                      async def __aenter__(self) -> Self:
                                          """Enter async context - automatically connects with empty stream for interactive use."""
                                          await self.connect()
                                          return self
                                  
                                      async def __aexit__(self, *args: object) -> None:
                                          """Exit async context - always disconnects."""
                                          await self.disconnect()
                                  

                                  query_cost instance-attribute

                                  query_cost: float = 0.0
                                  

                                  Cost in USD for the current/last query only (reset on each query() call).

                                  query_usage instance-attribute

                                  query_usage: Usage = Usage()
                                  

                                  Token usage for the current/last query only (reset on each query() call).

                                  session_cost instance-attribute

                                  session_cost: float = 0.0
                                  

                                  Cumulative cost in USD across all queries in this session.

                                  session_state instance-attribute

                                  session_state: SessionState = 'idle'
                                  

                                  Cumulative token usage across all queries in this session.

                                  status instance-attribute

                                  status: SDKStatus | None = None
                                  

                                  Current client status, or None when idle.

                                  __aenter__ async

                                  __aenter__() -> Self
                                  

                                  Enter async context - automatically connects with empty stream for interactive use.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def __aenter__(self) -> Self:
                                      """Enter async context - automatically connects with empty stream for interactive use."""
                                      await self.connect()
                                      return self
                                  

                                  __aexit__ async

                                  __aexit__(*args: object) -> None
                                  

                                  Exit async context - always disconnects.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def __aexit__(self, *args: object) -> None:
                                      """Exit async context - always disconnects."""
                                      await self.disconnect()
                                  

                                  __init__

                                  __init__(options: ClaudeAgentOptions | None = None, transport: Transport | None = None) -> None
                                  

                                  Initialize Claude SDK client.

                                  Source code in src/clawd_code_sdk/client.py
                                  def __init__(
                                      self,
                                      options: ClaudeAgentOptions | None = None,
                                      transport: Transport | None = None,
                                  ) -> None:
                                      """Initialize Claude SDK client."""
                                      options = options or ClaudeAgentOptions()
                                      self.options = options
                                      self._custom_transport = transport
                                      self._query: Query | None = None
                                      self._initialization_result: ClaudeCodeServerInfo | None = None
                                      self.session_usage: Usage = Usage()
                                      self.session_state: SessionState = "idle"
                                      """Cumulative token usage across all queries in this session."""
                                      self.query_usage: Usage = Usage()
                                      """Token usage for the current/last query only (reset on each query() call)."""
                                      self.session_cost: float = 0.0
                                      """Cumulative cost in USD across all queries in this session."""
                                      self.query_cost: float = 0.0
                                      """Cost in USD for the current/last query only (reset on each query() call)."""
                                      self.status: SDKStatus | None = None
                                      """Current client status, or None when idle."""
                                  
                                      self._logfire_prompt: str | None = None
                                      self._cli_version_checked = False
                                  

                                  apply_flag_settings async

                                  apply_flag_settings(settings: ClaudeCodeSettings) -> None
                                  

                                  Apply runtime settings overrides without restarting the session.

                                  Flag settings are an in-memory settings source that gets merged with other sources (user, project, etc.) to produce the effective settings.

                                  Parameters:

                                  Name Type Description Default
                                  settings ClaudeCodeSettings

                                  Settings to apply. Only fields that were set explicitly (and are not None) are sent: defaults would override every other settings source.

                                  required
                                  Source code in src/clawd_code_sdk/client.py
                                  async def apply_flag_settings(self, settings: ClaudeCodeSettings) -> None:
                                      """Apply runtime settings overrides without restarting the session.
                                  
                                      Flag settings are an in-memory settings source that gets merged with
                                      other sources (user, project, etc.) to produce the effective settings.
                                  
                                      Args:
                                          settings: Settings to apply. Only fields that were set explicitly (and are
                                              not None) are sent: defaults would override every other settings source.
                                      """
                                      query = self._ensure_connected()
                                      serialized = settings.model_dump(by_alias=True, exclude_unset=True, exclude_none=True)
                                      req = SDKControlApplyFlagSettingsRequest(settings=serialized)
                                      await query._send_control_request(req)
                                  

                                  background_tasks async

                                  background_tasks(tool_use_id: str | None = None) -> bool
                                  

                                  Move running foreground tasks (or a single tool use) to the background.

                                  Returns:

                                  Type Description
                                  bool

                                  Whether anything was backgrounded.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def background_tasks(self, tool_use_id: str | None = None) -> bool:
                                      """Move running foreground tasks (or a single tool use) to the background.
                                  
                                      Returns:
                                          Whether anything was backgrounded.
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlBackgroundTasksRequest(tool_use_id=tool_use_id)
                                      result = await query._send_control_request(request)
                                      return bool((result or {}).get("backgrounded", True))
                                  

                                  call_tool async

                                  call_tool(
                                      tool: str, arguments: dict[str, Any] | None = None, *, timeout: float | None = 600.0
                                  ) -> Any
                                  

                                  Call a tool on the server.

                                  Parameters:

                                  Name Type Description Default
                                  tool str

                                  The name of the tool to call

                                  required
                                  arguments dict[str, Any] | None

                                  Optional dictionary of arguments for the tool

                                  None
                                  timeout float | None

                                  Seconds to wait for the tool's result (None: no limit)

                                  600.0

                                  Returns:

                                  Type Description
                                  Any

                                  The result of the tool call

                                  Source code in src/clawd_code_sdk/client.py
                                  async def call_tool(
                                      self,
                                      tool: str,
                                      arguments: dict[str, Any] | None = None,
                                      *,
                                      timeout: float | None = 600.0,
                                  ) -> Any:
                                      """Call a tool on the server.
                                  
                                      Args:
                                          tool: The name of the tool to call
                                          arguments: Optional dictionary of arguments for the tool
                                          timeout: Seconds to wait for the tool's result (None: no limit)
                                  
                                      Returns:
                                          The result of the tool call
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlMcpCallRequest(tool=tool, arguments=arguments)
                                      return await query._send_control_request(request, timeout=timeout)
                                  

                                  cancel_async_message async

                                  cancel_async_message(message_uuid: str) -> None
                                  

                                  Drop a pending async user message from the command queue by uuid.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def cancel_async_message(self, message_uuid: str) -> None:
                                      """Drop a pending async user message from the command queue by uuid."""
                                      query = self._ensure_connected()
                                      request = SDKControlCancelAsyncMessageRequest(message_uuid=message_uuid)
                                      await query._send_control_request(request)
                                  

                                  channel_enable async

                                  channel_enable(server_name: str) -> None
                                  

                                  Enable MCP channel notifications for a marketplace plugin server.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def channel_enable(self, server_name: str) -> None:
                                      """Enable MCP channel notifications for a marketplace plugin server."""
                                      query = self._ensure_connected()
                                      req = SDKControlChannelEnableRequest(server_name=server_name)
                                      await query._send_control_request(req)
                                  

                                  claude_oauth_wait_for_completion async

                                  claude_oauth_wait_for_completion(
                                      *, timeout: float | None = None
                                  ) -> ClaudeOAuthWaitForCompletionResponse
                                  

                                  Wait for an in-progress Claude OAuth flow to complete.

                                  Parameters:

                                  Name Type Description Default
                                  timeout float | None

                                  Seconds to wait for the user to finish the browser login (None, the default: no limit).

                                  None

                                  Returns:

                                  Type Description
                                  ClaudeOAuthWaitForCompletionResponse

                                  Account details (email, organization, subscriptionType, etc.).

                                  Source code in src/clawd_code_sdk/client.py
                                  async def claude_oauth_wait_for_completion(
                                      self, *, timeout: float | None = None
                                  ) -> ClaudeOAuthWaitForCompletionResponse:
                                      """Wait for an in-progress Claude OAuth flow to complete.
                                  
                                      Args:
                                          timeout: Seconds to wait for the user to finish the browser login
                                              (None, the default: no limit).
                                  
                                      Returns:
                                          Account details (email, organization, subscriptionType, etc.).
                                      """
                                      query = self._ensure_connected()
                                      req = SDKControlClaudeOAuthWaitForCompletionRequest()
                                      data = await query._send_control_request(req, timeout=timeout)
                                      return ClaudeOAuthWaitForCompletionResponse.model_validate(data)
                                  

                                  connect async

                                  connect() -> None
                                  

                                  Connect to Claude Code CLI and initialize the session.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def connect(self) -> None:
                                      """Connect to Claude Code CLI and initialize the session."""
                                      # Use provided custom transport or create subprocess transport
                                      warn_if_can_use_tool_shadowed(self.options)
                                      self._query = Query.from_options(self.options, self._custom_transport)
                                      try:
                                          await self._query.transport.connect()
                                          await self._query.start()
                                          await self._initialize()
                                      except BaseException:
                                          # `async with` never reaches __aexit__ when connect() fails: don't leak the
                                          # CLI process and the reader task.
                                          # Shielded: an anyio scope that cancelled connect() stays cancelled.
                                          with anyio.CancelScope(shield=True), contextlib.suppress(Exception):
                                              await self.disconnect()  # the connect error is the one to see
                                          self._query = None
                                          raise
                                  

                                  disconnect async

                                  disconnect() -> None
                                  

                                  Disconnect from Claude.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def disconnect(self) -> None:
                                      """Disconnect from Claude."""
                                      if self._query:
                                          await self._query.close()
                                          self._query = None
                                  

                                  end_session async

                                  end_session() -> None
                                  

                                  End the current session.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def end_session(self) -> None:
                                      """End the current session."""
                                      query = self._ensure_connected()
                                      request = SDKControlEndSessionRequest()
                                      await query._send_control_request(request)
                                  

                                  generate_session_title async

                                  generate_session_title(
                                      description: str, *, persist: bool = False, timeout: float | None = 120.0
                                  ) -> str | None
                                  

                                  Generate a session title from description with the CLI's title model.

                                  Parameters:

                                  Name Type Description Default
                                  description str

                                  Text to title (the CLI reads its trailing ~1000 characters).

                                  required
                                  persist bool

                                  Store it as the current session's title; a session that has a title already returns that one.

                                  False
                                  timeout float | None

                                  Seconds to wait for the model (None: no limit).

                                  120.0

                                  Returns:

                                  Type Description
                                  str | None

                                  The title, or None when the text is too short to title.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def generate_session_title(
                                      self, description: str, *, persist: bool = False, timeout: float | None = 120.0
                                  ) -> str | None:
                                      """Generate a session title from ``description`` with the CLI's title model.
                                  
                                      Args:
                                          description: Text to title (the CLI reads its trailing ~1000 characters).
                                          persist: Store it as the current session's title; a session that has a title
                                              already returns that one.
                                          timeout: Seconds to wait for the model (None: no limit).
                                  
                                      Returns:
                                          The title, or None when the text is too short to title.
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlGenerateSessionTitleRequest(description=description, persist=persist)
                                      result = await query._send_control_request(request, timeout=timeout)
                                      title = (result or {}).get("title")
                                      return title if isinstance(title, str) and title else None
                                  

                                  get_binary_version async

                                  get_binary_version() -> dict[str, Any]
                                  

                                  Get version info of the running Claude Code binary.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def get_binary_version(self) -> dict[str, Any]:
                                      """Get version info of the running Claude Code binary."""
                                      query = self._ensure_connected()
                                      return await query._send_control_request(SDKControlGetBinaryVersionRequest())
                                  

                                  get_context_usage async

                                  get_context_usage(
                                      detail: Literal["summary", "full"] | None = None,
                                  ) -> SDKControlGetContextUsageResponse
                                  

                                  Get a breakdown of current context window usage by category.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def get_context_usage(
                                      self, detail: Literal["summary", "full"] | None = None
                                  ) -> SDKControlGetContextUsageResponse:
                                      """Get a breakdown of current context window usage by category."""
                                      query = self._ensure_connected()
                                      request = SDKControlGetContextUsageRequest(detail=detail)
                                      result = await query._send_control_request(request)
                                      return SDKControlGetContextUsageResponse.model_validate(result)
                                  

                                  get_file async

                                  get_file(path: str, max_bytes: int | None = None) -> SDKControlReadFileResponse
                                  

                                  Get the contents of a file from the server.

                                  Parameters:

                                  Name Type Description Default
                                  path str

                                  Path to the file to read

                                  required
                                  max_bytes int | None

                                  Maximum number of bytes to read (default: None, no limit)

                                  None

                                  Returns:

                                  Type Description
                                  SDKControlReadFileResponse

                                  The file contents and metadata

                                  Source code in src/clawd_code_sdk/client.py
                                  async def get_file(self, path: str, max_bytes: int | None = None) -> SDKControlReadFileResponse:
                                      """Get the contents of a file from the server.
                                  
                                      Args:
                                          path: Path to the file to read
                                          max_bytes: Maximum number of bytes to read (default: None, no limit)
                                  
                                      Returns:
                                          The file contents and metadata
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlReadFileRequest(path=path, max_bytes=max_bytes)
                                      result = await query._send_control_request(request)
                                      return SDKControlReadFileResponse.model_validate(result)
                                  

                                  get_hooks_listing async

                                  get_hooks_listing() -> dict[str, Any]
                                  

                                  Get the listing of configured hooks (same data as /hooks).

                                  Source code in src/clawd_code_sdk/client.py
                                  async def get_hooks_listing(self) -> dict[str, Any]:
                                      """Get the listing of configured hooks (same data as /hooks)."""
                                      query = self._ensure_connected()
                                      return await query._send_control_request(SDKControlGetHooksListingRequest())
                                  

                                  get_mcp_status async

                                  get_mcp_status() -> list[McpServerStatusEntry]
                                  

                                  Get current MCP server connection status.

                                  Returns:

                                  Type Description
                                  list[McpServerStatusEntry]

                                  Validated MCP status response containing server statuses,

                                  list[McpServerStatusEntry]

                                  configurations, tools, and connection information.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def get_mcp_status(self) -> list[McpServerStatusEntry]:
                                      """Get current MCP server connection status.
                                  
                                      Returns:
                                          Validated MCP status response containing server statuses,
                                          configurations, tools, and connection information.
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlMcpStatusRequest()
                                      result = await query._send_control_request(request)
                                      response = McpStatusResponse.model_validate(result)
                                      return response.mcp_servers
                                  

                                  get_server_info async

                                  get_server_info() -> ClaudeCodeServerInfo | None
                                  

                                  Get server initialization info including available commands and output styles.

                                  Returns initialization information from the Claude Code server including: - Available commands (slash commands, system commands, etc.) - Current and available output styles - Server capabilities

                                  Returns:

                                  Type Description
                                  ClaudeCodeServerInfo | None

                                  Parsed server info, or None if not yet initialized

                                  Source code in src/clawd_code_sdk/client.py
                                  async def get_server_info(self) -> ClaudeCodeServerInfo | None:
                                      """Get server initialization info including available commands and output styles.
                                  
                                      Returns initialization information from the Claude Code server including:
                                      - Available commands (slash commands, system commands, etc.)
                                      - Current and available output styles
                                      - Server capabilities
                                  
                                      Returns:
                                          Parsed server info, or None if not yet initialized
                                      """
                                      return self._initialization_result
                                  

                                  get_settings async

                                  get_settings() -> GetSettingsResponse
                                  

                                  Get the effective merged settings and raw per-source settings.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def get_settings(self) -> GetSettingsResponse:
                                      """Get the effective merged settings and raw per-source settings."""
                                      query = self._ensure_connected()
                                      request = SDKControlGetSettingsRequest()
                                      result = await query._send_control_request(request)
                                      return GetSettingsResponse.model_validate(result)
                                  

                                  get_task_output async

                                  get_task_output(task_id: str) -> SDKControlGetTaskOutputResponse
                                  

                                  Read the output collected so far for a background task.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def get_task_output(self, task_id: str) -> SDKControlGetTaskOutputResponse:
                                      """Read the output collected so far for a background task."""
                                      query = self._ensure_connected()
                                      request = SDKControlGetTaskOutputRequest(task_id=task_id)
                                      result = await query._send_control_request(request)
                                      return SDKControlGetTaskOutputResponse.model_validate(result)
                                  

                                  get_usage async

                                  get_usage(*, skip_behaviors: bool = True) -> SDKControlGetUsageResponse
                                  

                                  Get session usage and plan rate-limit windows (experimental, shape may change).

                                  Parameters:

                                  Name Type Description Default
                                  skip_behaviors bool

                                  Skip the (slow) scan of local transcripts that fills behaviors.

                                  True
                                  Source code in src/clawd_code_sdk/client.py
                                  async def get_usage(self, *, skip_behaviors: bool = True) -> SDKControlGetUsageResponse:
                                      """Get session usage and plan rate-limit windows (experimental, shape may change).
                                  
                                      Args:
                                          skip_behaviors: Skip the (slow) scan of local transcripts that fills
                                              ``behaviors``.
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlGetUsageRequest(skip_behaviors=skip_behaviors or None)
                                      result = await query._send_control_request(request)
                                      return SDKControlGetUsageResponse.model_validate(result)
                                  

                                  interrupt async

                                  interrupt(*, cancel_queued: bool = False) -> SDKControlInterruptResponse | None
                                  

                                  Send interrupt signal (only works with streaming mode).

                                  Parameters:

                                  Name Type Description Default
                                  cancel_queued bool

                                  Also cancel queued (not yet started) user messages.

                                  False

                                  Returns:

                                  Type Description
                                  SDKControlInterruptResponse | None

                                  Which queued messages are still queued / were cancelled

                                  SDKControlInterruptResponse | None

                                  (None on CLIs that don't report it).

                                  Source code in src/clawd_code_sdk/client.py
                                  async def interrupt(self, *, cancel_queued: bool = False) -> SDKControlInterruptResponse | None:
                                      """Send interrupt signal (only works with streaming mode).
                                  
                                      Args:
                                          cancel_queued: Also cancel queued (not yet started) user messages.
                                  
                                      Returns:
                                          Which queued messages are still queued / were cancelled
                                          (None on CLIs that don't report it).
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlInterruptRequest(cancel_queued=cancel_queued or None)
                                      result = await query._send_control_request(request)
                                      return SDKControlInterruptResponse.model_validate(result) if result else None
                                  

                                  list_models async

                                  list_models() -> list[ClaudeCodeModelInfo]
                                  

                                  Fetch the list of available models from the CLI.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def list_models(self) -> list[ClaudeCodeModelInfo]:
                                      """Fetch the list of available models from the CLI."""
                                      query = self._ensure_connected()
                                      result = await query._send_control_request(SDKControlListModelsRequest())
                                      return [ClaudeCodeModelInfo.model_validate(m) for m in (result or {}).get("models", [])]
                                  

                                  list_permission_rules async

                                  list_permission_rules() -> dict[str, Any]
                                  

                                  List the effective permission rules (raw state payload).

                                  Source code in src/clawd_code_sdk/client.py
                                  async def list_permission_rules(self) -> dict[str, Any]:
                                      """List the effective permission rules (raw ``state`` payload)."""
                                      query = self._ensure_connected()
                                      result = await query._send_control_request(SDKControlListPermissionRulesRequest())
                                      state: dict[str, Any] = (result or {}).get("state", {})
                                      return state
                                  

                                  mcp_authenticate async

                                  mcp_authenticate(server_name: str) -> McpAuthenticateResponse
                                  

                                  Trigger OAuth authentication for an MCP server.

                                  Returns:

                                  Type Description
                                  McpAuthenticateResponse

                                  Response indicating whether user action is required and the auth URL if so.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def mcp_authenticate(self, server_name: str) -> McpAuthenticateResponse:
                                      """Trigger OAuth authentication for an MCP server.
                                  
                                      Returns:
                                          Response indicating whether user action is required and the auth URL if so.
                                      """
                                      query = self._ensure_connected()
                                      req = SDKControlMcpAuthenticateRequest(server_name=server_name)
                                      result = await query._send_control_request(req)
                                      return McpAuthenticateResponse.model_validate(result)
                                  

                                  mcp_clear_auth async

                                  mcp_clear_auth(server_name: str) -> None
                                  

                                  Clear OAuth credentials for an MCP server.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def mcp_clear_auth(self, server_name: str) -> None:
                                      """Clear OAuth credentials for an MCP server."""
                                      query = self._ensure_connected()
                                      req = SDKControlMcpClearAuthRequest(server_name=server_name)
                                      await query._send_control_request(req)
                                  

                                  mcp_oauth_callback_url async

                                  mcp_oauth_callback_url(server_name: str, callback_url: str) -> None
                                  

                                  Provide an OAuth redirect callback URL to complete an MCP server OAuth flow.

                                  After the user completes browser-based OAuth, call this with the full redirect URL (containing the authorization code) to finish the flow.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def mcp_oauth_callback_url(self, server_name: str, callback_url: str) -> None:
                                      """Provide an OAuth redirect callback URL to complete an MCP server OAuth flow.
                                  
                                      After the user completes browser-based OAuth, call this with the full
                                      redirect URL (containing the authorization code) to finish the flow.
                                      """
                                      query = self._ensure_connected()
                                      req = SDKControlMcpOAuthCallbackUrlRequest(
                                          server_name=server_name, callback_url=callback_url
                                      )
                                      await query._send_control_request(req)
                                  

                                  mcp_reconnect async

                                  mcp_reconnect(server_name: str) -> None
                                  

                                  Reconnect to an MCP server.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def mcp_reconnect(self, server_name: str) -> None:
                                      """Reconnect to an MCP server."""
                                      query = self._ensure_connected()
                                      request = SDKControlMcpReconnectRequest(server_name=server_name)
                                      await query._send_control_request(request)
                                  

                                  mcp_toggle async

                                  mcp_toggle(server_name: str, *, enabled: bool) -> None
                                  

                                  Enable or disable an MCP server.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def mcp_toggle(self, server_name: str, *, enabled: bool) -> None:
                                      """Enable or disable an MCP server."""
                                      query = self._ensure_connected()
                                      request = SDKControlMcpToggleRequest(server_name=server_name, enabled=enabled)
                                      await query._send_control_request(request)
                                  

                                  one_shot async classmethod

                                  one_shot(
                                      *prompts: str | UserPrompt,
                                      options: ClaudeAgentOptions | None = None,
                                      transport: Transport | None = None,
                                  ) -> AsyncIterator[Message]
                                  

                                  One-shot query convenience method.

                                  Parameters:

                                  Name Type Description Default
                                  *prompts str | UserPrompt

                                  One or more content blocks to send.

                                  ()
                                  options ClaudeAgentOptions | None

                                  Optional configuration.

                                  None
                                  transport Transport | None

                                  Optional transport implementation override.

                                  None

                                  Yields:

                                  Type Description
                                  AsyncIterator[Message]

                                  Messages from the conversation

                                  Source code in src/clawd_code_sdk/client.py
                                  @classmethod
                                  async def one_shot(
                                      cls,
                                      *prompts: str | UserPrompt,
                                      options: ClaudeAgentOptions | None = None,
                                      transport: Transport | None = None,
                                  ) -> AsyncIterator[Message]:
                                      """One-shot query convenience method.
                                  
                                      Args:
                                          *prompts: One or more content blocks to send.
                                          options: Optional configuration.
                                          transport: Optional transport implementation override.
                                  
                                      Yields:
                                          Messages from the conversation
                                      """
                                      client = cls(options=options, transport=transport)
                                      try:
                                          await client.connect()
                                          await client.query(*prompts)
                                          async for message in client.receive_response():
                                              yield message
                                      finally:
                                          await client.disconnect()
                                  

                                  query async

                                  query(
                                      *prompts: str | UserPrompt,
                                      session_id: str = "default",
                                      parent_tool_use_id: str | None = None,
                                      should_query: bool = True,
                                      priority: MessagePriority | None = None,
                                      uuid: str | None = None,
                                  ) -> None
                                  

                                  Send a new user message with one or more content blocks.

                                  Starts a new query: query_usage and query_cost count from here.

                                  Parameters:

                                  Name Type Description Default
                                  *prompts str | UserPrompt

                                  One or more content blocks. Strings are converted to UserTextPrompt automatically. Pass multiple to combine, e.g. query(image_prompt, "What's in this image?").

                                  ()
                                  session_id str

                                  Session identifier for the message.

                                  'default'
                                  parent_tool_use_id str | None

                                  If responding to a tool use, the tool_use block ID.

                                  None
                                  should_query bool

                                  Whether to query the model for a response. Defaults to True.

                                  True
                                  priority MessagePriority | None

                                  The priority of the message. Defaults to None.

                                  None
                                  uuid str | None

                                  ID of the message; the CLI then reports its progress as CommandLifecycleMessage frames and names it in results.

                                  None
                                  Source code in src/clawd_code_sdk/client.py
                                  async def query(
                                      self,
                                      *prompts: str | UserPrompt,
                                      session_id: str = "default",
                                      parent_tool_use_id: str | None = None,
                                      should_query: bool = True,
                                      priority: MessagePriority | None = None,
                                      uuid: str | None = None,
                                  ) -> None:
                                      """Send a new user message with one or more content blocks.
                                  
                                      Starts a new query: ``query_usage`` and ``query_cost`` count from here.
                                  
                                      Args:
                                          *prompts: One or more content blocks. Strings are converted to
                                              UserTextPrompt automatically. Pass multiple to combine, e.g.
                                              ``query(image_prompt, "What's in this image?")``.
                                          session_id: Session identifier for the message.
                                          parent_tool_use_id: If responding to a tool use, the tool_use block ID.
                                          should_query: Whether to query the model for a response. Defaults to True.
                                          priority: The priority of the message. Defaults to None.
                                          uuid: ID of the message; the CLI then reports its progress as
                                              ``CommandLifecycleMessage`` frames and names it in results.
                                      """
                                      prompt = prompts[0] if prompts else None
                                      self._logfire_prompt = str(prompt)
                                      self.query_usage.reset()
                                      self.query_cost = 0.0
                                      await self._send_user_message(
                                          prompts,
                                          session_id=session_id,
                                          parent_tool_use_id=parent_tool_use_id,
                                          should_query=should_query,
                                          priority=priority,
                                          uuid=uuid,
                                      )
                                  

                                  read_mcp_resource async

                                  read_mcp_resource(server_name: str, uri: str) -> SDKControlMcpReadResourceResponse
                                  

                                  Read a resource from a connected MCP server.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def read_mcp_resource(
                                      self, server_name: str, uri: str
                                  ) -> SDKControlMcpReadResourceResponse:
                                      """Read a resource from a connected MCP server."""
                                      query = self._ensure_connected()
                                      request = SDKControlMcpReadResourceRequest(server_name=server_name, uri=uri)
                                      result = await query._send_control_request(request)
                                      return SDKControlMcpReadResourceResponse.model_validate(result)
                                  

                                  receive_messages async

                                  receive_messages() -> AsyncIterator[Message]
                                  

                                  Receive all messages from Claude.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def receive_messages(self) -> AsyncIterator[Message]:
                                      """Receive all messages from Claude."""
                                      query = self._ensure_connected()
                                      async for data in query.receive_messages():
                                          try:
                                              message = parse_message(data)
                                          except MessageParseError:
                                              # A newer CLI may send message types this SDK does not model yet: skip
                                              # them unless CLAWD_STRICT_MESSAGES is set. Malformed known types raise.
                                              if (kind := unknown_message_kind(data)) is None or strict_messages():
                                                  raise
                                              if kind not in _warned_unknown_kinds:
                                                  _warned_unknown_kinds.add(kind)
                                                  logger.warning(
                                                      "Skipping unknown Claude Code message type %r (set %s=1 to raise)",
                                                      kind,
                                                      STRICT_MESSAGES_ENV,
                                                  )
                                              continue
                                          match message:
                                              case AssistantMessage():
                                                  message.raise_if_api_error()
                                              case StatusSystemMessage(status=status):
                                                  self.status = status
                                              case InitSystemMessage(claude_code_version=version) if (
                                                  not self._cli_version_checked
                                              ):
                                                  check_claude_version(version)
                                                  self._cli_version_checked = True
                                              case SessionStateChangedMessage(state=state):
                                                  self.session_state = state
                                              case (
                                                  ResultSuccessMessage(usage=usage, total_cost_usd=total_cost)
                                                  | ResultErrorMessage(usage=usage, total_cost_usd=total_cost)
                                              ):
                                                  self.query_usage.accumulate(usage)
                                                  self.session_usage.accumulate(usage)
                                                  # total_cost_usd is cumulative; a query adds the delta of each of its
                                                  # results (a steered query has one per cycle)
                                                  self.query_cost += total_cost - self.session_cost
                                                  self.session_cost = total_cost
                                          yield message
                                  

                                  receive_response async

                                  receive_response() -> AsyncIterator[Message]
                                  

                                  Receive messages from Claude until the response is complete.

                                  This async iterator yields all messages in sequence and automatically terminates when the session transitions to idle state — the authoritative signal that the CLI has fully finished its turn (held-back results flushed, background agent loops exited).

                                  Stopping Behavior: - Yields each message as it's received - Terminates after yielding a SessionStateChangedMessage with state='idle' - The final message in the collected list will always be the idle state-change message

                                  Yields:

                                  Name Type Description
                                  Message AsyncIterator[Message]

                                  Each message received

                                  Note

                                  To collect all messages: messages = [msg async for msg in client.receive_response()]

                                  Source code in src/clawd_code_sdk/client.py
                                  async def receive_response(self) -> AsyncIterator[Message]:
                                      """Receive messages from Claude until the response is complete.
                                  
                                      This async iterator yields all messages in sequence and automatically
                                      terminates when the session transitions to ``idle`` state — the
                                      authoritative signal that the CLI has fully finished its turn
                                      (held-back results flushed, background agent loops exited).
                                  
                                      **Stopping Behavior:**
                                      - Yields each message as it's received
                                      - Terminates after yielding a ``SessionStateChangedMessage`` with
                                        ``state='idle'``
                                      - The final message in the collected list will always be the idle
                                        state-change message
                                  
                                      Yields:
                                          Message: Each message received
                                  
                                      Note:
                                          To collect all messages: `messages = [msg async for msg in client.receive_response()]`
                                      """
                                      async for message in self.receive_messages():
                                          yield message
                                          if isinstance(message, SessionStateChangedMessage) and message.state == "idle":
                                              return
                                  

                                  register_repo_root async

                                  register_repo_root(
                                      directory: str | Path,
                                      *,
                                      reload_claude_md: bool | None = None,
                                      reload_plugins: bool | None = None,
                                      reload_skills: bool | None = None,
                                  ) -> None
                                  

                                  Register an additional repository root for the session (like /add-dir).

                                  Source code in src/clawd_code_sdk/client.py
                                  async def register_repo_root(
                                      self,
                                      directory: str | Path,
                                      *,
                                      reload_claude_md: bool | None = None,
                                      reload_plugins: bool | None = None,
                                      reload_skills: bool | None = None,
                                  ) -> None:
                                      """Register an additional repository root for the session (like /add-dir)."""
                                      query = self._ensure_connected()
                                      request = SDKControlRegisterRepoRootRequest(
                                          directory=str(directory),
                                          reload_claude_md=reload_claude_md,
                                          reload_plugins=reload_plugins,
                                          reload_skills=reload_skills,
                                      )
                                      await query._send_control_request(request)
                                  

                                  reload_output_styles async

                                  reload_output_styles() -> list[str]
                                  

                                  Re-scan output styles from disk and return the available style names.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def reload_output_styles(self) -> list[str]:
                                      """Re-scan output styles from disk and return the available style names."""
                                      query = self._ensure_connected()
                                      result = await query._send_control_request(SDKControlReloadOutputStylesRequest())
                                      return SDKControlReloadOutputStylesResponse.model_validate(result).available_output_styles
                                  

                                  reload_skills async

                                  reload_skills() -> list[ClaudeCodeCommandInfo]
                                  

                                  Re-scan skills from disk and return the refreshed skill list.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def reload_skills(self) -> list[ClaudeCodeCommandInfo]:
                                      """Re-scan skills from disk and return the refreshed skill list."""
                                      query = self._ensure_connected()
                                      result = await query._send_control_request(SDKControlReloadSkillsRequest())
                                      return SDKControlReloadSkillsResponse.model_validate(result).skills
                                  

                                  remote_control async

                                  remote_control(*, enabled: bool) -> RemoteControlResponse | None
                                  

                                  Toggle the remote control REPL bridge for external session access.

                                  When enabled, starts a bridge that allows remote clients to send prompts, permission responses, interrupts, and model changes into the session.

                                  Returns:

                                  Type Description
                                  RemoteControlResponse | None

                                  A RemoteControlResponse with session URLs and environment ID

                                  RemoteControlResponse | None

                                  when enabling, or None when disabling.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def remote_control(self, *, enabled: bool) -> RemoteControlResponse | None:
                                      """Toggle the remote control REPL bridge for external session access.
                                  
                                      When enabled, starts a bridge that allows remote clients to send prompts,
                                      permission responses, interrupts, and model changes into the session.
                                  
                                      Returns:
                                          A ``RemoteControlResponse`` with session URLs and environment ID
                                          when enabling, or ``None`` when disabling.
                                      """
                                      query = self._ensure_connected()
                                      req = SDKControlRemoteControlRequest(enabled=enabled)
                                      result = await query._send_control_request(req)
                                      if not result:
                                          return None
                                      return RemoteControlResponse.model_validate(result)
                                  

                                  rewind_files async

                                  rewind_files(user_message_id: str) -> None
                                  

                                  Rewind tracked files to their state at a specific user message.

                                  Requires
                                  • enable_file_checkpointing=True to track file changes
                                  • extra_args={"replay-user-messages": None} to receive UserMessage objects with uuid in the response stream

                                  Parameters:

                                  Name Type Description Default
                                  user_message_id str

                                  UUID of the user message to rewind to. This should be the uuid field from a UserMessage received during the conversation.

                                  required
                                  Example
                                  options = ClaudeAgentOptions(
                                      enable_file_checkpointing=True,
                                      extra_args={"replay-user-messages": None},
                                  )
                                  async with ClaudeSDKClient(options) as client:
                                      await client.query("Make some changes to my files")
                                      async for msg in client.receive_response():
                                          if isinstance(msg, UserMessage) and msg.uuid:
                                              checkpoint_id = msg.uuid  # Save this for later
                                  
                                      # Later, rewind to that point
                                      await client.rewind_files(checkpoint_id)
                                  
                                  Source code in src/clawd_code_sdk/client.py
                                  async def rewind_files(self, user_message_id: str) -> None:
                                      """Rewind tracked files to their state at a specific user message.
                                  
                                      Requires:
                                          - `enable_file_checkpointing=True` to track file changes
                                          - `extra_args={"replay-user-messages": None}` to receive UserMessage
                                            objects with `uuid` in the response stream
                                  
                                      Args:
                                          user_message_id: UUID of the user message to rewind to. This should be
                                              the `uuid` field from a `UserMessage` received during the conversation.
                                  
                                      Example:
                                          ```python
                                          options = ClaudeAgentOptions(
                                              enable_file_checkpointing=True,
                                              extra_args={"replay-user-messages": None},
                                          )
                                          async with ClaudeSDKClient(options) as client:
                                              await client.query("Make some changes to my files")
                                              async for msg in client.receive_response():
                                                  if isinstance(msg, UserMessage) and msg.uuid:
                                                      checkpoint_id = msg.uuid  # Save this for later
                                  
                                              # Later, rewind to that point
                                              await client.rewind_files(checkpoint_id)
                                          ```
                                      """
                                      query = self._ensure_connected()
                                      req = SDKControlRewindFilesRequest(user_message_id=user_message_id)
                                      await query._send_control_request(req)
                                  

                                  seed_read_state async

                                  seed_read_state(path: str, mtime: int) -> None
                                  

                                  Seed the CLI's readFileState cache with a path+mtime entry.

                                  Use when the client observed a Read that has since been removed from context (e.g. by snip), so a subsequent Edit won't fail "file not read yet". If the file changed on disk since the given mtime, the seed is skipped and Edit will correctly require a fresh Read.

                                  Parameters:

                                  Name Type Description Default
                                  path str

                                  Path to the file that was previously Read

                                  required
                                  mtime int

                                  File mtime (floored ms) at the time of the observed Read

                                  required
                                  Source code in src/clawd_code_sdk/client.py
                                  async def seed_read_state(self, path: str, mtime: int) -> None:
                                      """Seed the CLI's readFileState cache with a path+mtime entry.
                                  
                                      Use when the client observed a Read that has since been removed from context
                                      (e.g. by snip), so a subsequent Edit won't fail "file not read yet".
                                      If the file changed on disk since the given mtime, the seed is skipped
                                      and Edit will correctly require a fresh Read.
                                  
                                      Args:
                                          path: Path to the file that was previously Read
                                          mtime: File mtime (floored ms) at the time of the observed Read
                                      """
                                      query = self._ensure_connected()
                                      req = SDKControlSeedReadStateRequest(path=path, mtime=mtime)
                                      await query._send_control_request(req)
                                  

                                  set_max_thinking_tokens async

                                  set_max_thinking_tokens(
                                      max_thinking_tokens: int | None,
                                      thinking_display: Literal["summarized", "omitted", "highlights"] | None = None,
                                  ) -> None
                                  

                                  Set the maximum number of thinking tokens (and optionally the display mode).

                                  Source code in src/clawd_code_sdk/client.py
                                  async def set_max_thinking_tokens(
                                      self,
                                      max_thinking_tokens: int | None,
                                      thinking_display: Literal["summarized", "omitted", "highlights"] | None = None,
                                  ) -> None:
                                      """Set the maximum number of thinking tokens (and optionally the display mode)."""
                                      query = self._ensure_connected()
                                      request = SDKControlSetMaxThinkingTokensRequest(
                                          max_thinking_tokens=max_thinking_tokens, thinking_display=thinking_display
                                      )
                                      await query._send_control_request(request)
                                  

                                  set_mcp_servers async

                                  set_mcp_servers(servers: dict[str, ExternalMcpServerConfig]) -> McpSetServersResult
                                  

                                  Add, replace, or remove MCP servers dynamically mid-session.

                                  Allows dynamic registration of MCP servers without restarting the session. Pass an empty dict to remove all dynamic servers.

                                  The server name is automatically injected from the dict key into each config, so callers don't need to specify it redundantly.

                                  Parameters:

                                  Name Type Description Default
                                  servers dict[str, ExternalMcpServerConfig]

                                  Dictionary mapping server names to server configurations. Values are typed MCP server configs (McpStdioServerConfig, McpSSEServerConfig, McpHttpServerConfig, or McpSdkServerConfig).

                                  required

                                  Returns:

                                  Type Description
                                  McpSetServersResult

                                  Dictionary with results:

                                  McpSetServersResult
                                  • 'added': List of server names that were added
                                  McpSetServersResult
                                  • 'removed': List of server names that were removed
                                  McpSetServersResult
                                  • 'errors': Dict mapping server names to error messages (if any)
                                  Source code in src/clawd_code_sdk/client.py
                                  async def set_mcp_servers(
                                      self, servers: dict[str, ExternalMcpServerConfig]
                                  ) -> McpSetServersResult:
                                      """Add, replace, or remove MCP servers dynamically mid-session.
                                  
                                      Allows dynamic registration of MCP servers without restarting the session.
                                      Pass an empty dict to remove all dynamic servers.
                                  
                                      The server name is automatically injected from the dict key into each
                                      config, so callers don't need to specify it redundantly.
                                  
                                      Args:
                                          servers: Dictionary mapping server names to server configurations.
                                              Values are typed MCP server configs (McpStdioServerConfig,
                                              McpSSEServerConfig, McpHttpServerConfig, or McpSdkServerConfig).
                                  
                                      Returns:
                                          Dictionary with results:
                                          - 'added': List of server names that were added
                                          - 'removed': List of server names that were removed
                                          - 'errors': Dict mapping server names to error messages (if any)
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlMcpSetServersRequest(servers=servers)
                                      result = await query._send_control_request(request)
                                      return McpSetServersResult.model_validate(result)
                                  

                                  set_model async

                                  set_model(model: str | None = None) -> None
                                  

                                  Change the AI model during conversation (only works with streaming mode).

                                  Parameters:

                                  Name Type Description Default
                                  model str | None

                                  The model to use, or None to use default. Example: 'claude-sonnet-4-5'

                                  None
                                  Source code in src/clawd_code_sdk/client.py
                                  async def set_model(self, model: str | None = None) -> None:
                                      """Change the AI model during conversation (only works with streaming mode).
                                  
                                      Args:
                                          model: The model to use, or None to use default. Example: 'claude-sonnet-4-5'
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlSetModelRequest(model=model)
                                      await query._send_control_request(request)
                                  

                                  set_permission_mode async

                                  set_permission_mode(mode: PermissionMode) -> SDKControlSetPermissionModeResponse | None
                                  

                                  Change permission mode during conversation (only works with streaming mode).

                                  Parameters:

                                  Name Type Description Default
                                  mode PermissionMode

                                  The permission mode to set. Valid options: - 'default': CLI prompts for dangerous tools - 'acceptEdits': Auto-accept file edits - 'plan': Plan mode for planning tasks - 'bypassPermissions': Allow all tools (use with caution)

                                  required

                                  Returns:

                                  Type Description
                                  SDKControlSetPermissionModeResponse | None

                                  The mode now in effect (it can differ from mode), or None if the

                                  SDKControlSetPermissionModeResponse | None

                                  CLI answered without a payload (before Claude Code 2.1.332).

                                  Source code in src/clawd_code_sdk/client.py
                                  async def set_permission_mode(
                                      self, mode: PermissionMode
                                  ) -> SDKControlSetPermissionModeResponse | None:
                                      """Change permission mode during conversation (only works with streaming mode).
                                  
                                      Args:
                                          mode: The permission mode to set. Valid options:
                                              - 'default': CLI prompts for dangerous tools
                                              - 'acceptEdits': Auto-accept file edits
                                              - 'plan': Plan mode for planning tasks
                                              - 'bypassPermissions': Allow all tools (use with caution)
                                  
                                      Returns:
                                          The mode now in effect (it can differ from ``mode``), or None if the
                                          CLI answered without a payload (before Claude Code 2.1.332).
                                      """
                                      query = self._ensure_connected()
                                      request = SDKControlSetPermissionModeRequest(mode=mode)
                                      result = await query._send_control_request(request)
                                      return SDKControlSetPermissionModeResponse.model_validate(result) if result else None
                                  

                                  side_question async

                                  side_question(question: str, *, timeout: float | None = 600.0) -> SideQuestionResponse
                                  

                                  Send a side question to the model using the current conversation context.

                                  The model answers the question without it being added to the main conversation history.

                                  Parameters:

                                  Name Type Description Default
                                  question str

                                  The question to ask the model.

                                  required
                                  timeout float | None

                                  Seconds to wait for the answer (None: no limit).

                                  600.0

                                  Returns:

                                  Type Description
                                  SideQuestionResponse

                                  The model's answer, or None if no context was available.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def side_question(
                                      self, question: str, *, timeout: float | None = 600.0
                                  ) -> SideQuestionResponse:
                                      """Send a side question to the model using the current conversation context.
                                  
                                      The model answers the question without it being added to the main
                                      conversation history.
                                  
                                      Args:
                                          question: The question to ask the model.
                                          timeout: Seconds to wait for the answer (None: no limit).
                                  
                                      Returns:
                                          The model's answer, or None if no context was available.
                                      """
                                      query = self._ensure_connected()
                                      req = SDKControlSideQuestionRequest(question=question)
                                      data = await query._send_control_request(req, timeout=timeout)
                                      return SideQuestionResponse.model_validate(data)
                                  

                                  steer async

                                  steer(
                                      *prompts: str | UserPrompt, priority: MessagePriority = "now", session_id: str = "default"
                                  ) -> str
                                  

                                  Send a user message into the running query instead of starting a new one.

                                  query_usage and query_cost keep counting the running query. With "now" the CLI takes the message in at once: it ends the cycle that is generating (which reports a result of its own) or moves a running foreground tool to the background, and works on the message in the same query. "later" waits for the running cycle (e.g. while a permission request is open).

                                  Parameters:

                                  Name Type Description Default
                                  *prompts str | UserPrompt

                                  Content blocks of the message (strings become text blocks).

                                  ()
                                  priority MessagePriority

                                  When the CLI takes the message in.

                                  'now'
                                  session_id str

                                  Session identifier for the message.

                                  'default'

                                  Returns:

                                  Type Description
                                  str

                                  The message's uuid, which CommandLifecycleMessage.command_uuid and the

                                  str

                                  results' user_message_uuids refer to.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def steer(
                                      self,
                                      *prompts: str | UserPrompt,
                                      priority: MessagePriority = "now",
                                      session_id: str = "default",
                                  ) -> str:
                                      """Send a user message into the running query instead of starting a new one.
                                  
                                      ``query_usage`` and ``query_cost`` keep counting the running query. With
                                      ``"now"`` the CLI takes the message in at once: it ends the cycle that is
                                      generating (which reports a result of its own) or moves a running foreground
                                      tool to the background, and works on the message in the same query. ``"later"``
                                      waits for the running cycle (e.g. while a permission request is open).
                                  
                                      Args:
                                          *prompts: Content blocks of the message (strings become text blocks).
                                          priority: When the CLI takes the message in.
                                          session_id: Session identifier for the message.
                                  
                                      Returns:
                                          The message's uuid, which ``CommandLifecycleMessage.command_uuid`` and the
                                          results' ``user_message_uuids`` refer to.
                                      """
                                      message_uuid = str(uuid4())
                                      await self._send_user_message(
                                          prompts, session_id=session_id, priority=priority, uuid=message_uuid
                                      )
                                      return message_uuid
                                  

                                  stop_task async

                                  stop_task(task_id: str) -> None
                                  

                                  Stop a running task.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def stop_task(self, task_id: str) -> None:
                                      """Stop a running task."""
                                      query = self._ensure_connected()
                                      request = SDKControlStopTaskRequest(task_id=task_id)
                                      await query._send_control_request(request)
                                  

                                  supported_agents async

                                  supported_agents() -> list[ClaudeCodeAgentInfo]
                                  

                                  Get the list of available subagents for the current session.

                                  Returns:

                                  Type Description
                                  list[ClaudeCodeAgentInfo]

                                  List of available agents with their names, descriptions, and configuration.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def supported_agents(self) -> list[ClaudeCodeAgentInfo]:
                                      """Get the list of available subagents for the current session.
                                  
                                      Returns:
                                          List of available agents with their names, descriptions, and configuration.
                                      """
                                      if self._initialization_result is None:
                                          raise RuntimeError("Not initialized. Call connect() first.")
                                      return self._initialization_result.agents
                                  

                                  update_settings async

                                  update_settings(source: Literal['localSettings', 'userSettings'], settings: dict[str, Any]) -> None
                                  

                                  Persist settings to the local or user settings file.

                                  Source code in src/clawd_code_sdk/client.py
                                  async def update_settings(
                                      self,
                                      source: Literal["localSettings", "userSettings"],
                                      settings: dict[str, Any],
                                  ) -> None:
                                      """Persist settings to the local or user settings file."""
                                      query = self._ensure_connected()
                                      request = SDKControlUpdateSettingsRequest(source=source, settings=settings)
                                      await query._send_control_request(request)
                                  

                                  ClaudeSDKError

                                  Bases: Exception

                                  Base exception for all Claude SDK errors.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class ClaudeSDKError(Exception):
                                      """Base exception for all Claude SDK errors."""
                                  

                                  ContinueLatest dataclass

                                  Bases: BaseSessionConfig

                                  Continue the most recent conversation.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  @dataclass(kw_only=True)
                                  class ContinueLatest(BaseSessionConfig):
                                      """Continue the most recent conversation."""
                                  
                                      mode: Literal["continue"] = "continue"
                                      fork: bool = False
                                      """If True, fork to a new session ID instead of continuing in-place."""
                                  

                                  fork class-attribute instance-attribute

                                  fork: bool = False
                                  

                                  If True, fork to a new session ID instead of continuing in-place.

                                  ConversationTurn dataclass

                                  Collected result of a single send/receive cycle.

                                  Source code in src/clawd_code_sdk/session.py
                                  @dataclass(frozen=True)
                                  class ConversationTurn:
                                      """Collected result of a single send/receive cycle."""
                                  
                                      messages: tuple[Message, ...]
                                      result: ResultMessage
                                      text: str
                                      tool_calls: tuple[ToolCallSummary, ...]
                                      cost_usd: float | None
                                      duration_ms: int
                                  

                                  Filesystem

                                  Bases: ClaudeCodeBaseModel

                                  Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation.

                                  Source code in src/clawd_code_sdk/models/settings.py
                                  class Filesystem(ClaudeCodeBaseModel):
                                      """Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation."""
                                  
                                      model_config = ConfigDict(
                                          extra="forbid",
                                      )
                                      allow_write: list[AllowWriteItem] | None = Field(None, alias="allowWrite")
                                      """
                                      Paths where subprocesses are allowed to write. Supports prefixes: // (absolute), ~/ (home directory), / (relative to settings file), ./ or no prefix (relative path). See https://code.claude.com/docs/en/sandboxing#granting-subprocess-write-access-to-specific-paths
                                      """
                                      deny_write: list[DenyWriteItem] | None = Field(None, alias="denyWrite")
                                      """
                                      Paths where subprocesses are explicitly denied write access. Takes precedence over allowWrite. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation
                                      """
                                      deny_read: list[DenyReadItem] | None = Field(None, alias="denyRead")
                                      """
                                      Paths where subprocesses are explicitly denied read access. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation
                                      """
                                      allow_read: list[AllowReadItem] | None = Field(None, alias="allowRead")
                                      """
                                      Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths. See https://code.claude.com/docs/en/sandboxing#granting-subprocess-write-access-to-specific-paths
                                      """
                                      allow_managed_read_paths_only: bool | None = Field(None, alias="allowManagedReadPathsOnly")
                                      """
                                      (Managed settings only) When true, only allowRead paths from managed settings are used; user, project, and local allowRead entries are ignored. denyRead still merges from all sources. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation
                                      """
                                      disabled: bool | None = False
                                      """
                                      Skip filesystem isolation while keeping network isolation: sandboxed commands get unrestricted read and write access to the host filesystem, and network egress stays confined to network.allowedDomains. Only honored from user, managed, or CLI --settings settings (default: false). Requires Claude Code v2.1.216 or later. See https://code.claude.com/docs/en/sandboxing#disable-filesystem-isolation
                                      """
                                  

                                  allow_managed_read_paths_only class-attribute instance-attribute

                                  allow_managed_read_paths_only: bool | None = Field(None, alias='allowManagedReadPathsOnly')
                                  

                                  (Managed settings only) When true, only allowRead paths from managed settings are used; user, project, and local allowRead entries are ignored. denyRead still merges from all sources. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation

                                  allow_read class-attribute instance-attribute

                                  allow_read: list[AllowReadItem] | None = Field(None, alias='allowRead')
                                  

                                  Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths. See https://code.claude.com/docs/en/sandboxing#granting-subprocess-write-access-to-specific-paths

                                  allow_write class-attribute instance-attribute

                                  allow_write: list[AllowWriteItem] | None = Field(None, alias='allowWrite')
                                  

                                  Paths where subprocesses are allowed to write. Supports prefixes: // (absolute), ~/ (home directory), / (relative to settings file), ./ or no prefix (relative path). See https://code.claude.com/docs/en/sandboxing#granting-subprocess-write-access-to-specific-paths

                                  deny_read class-attribute instance-attribute

                                  deny_read: list[DenyReadItem] | None = Field(None, alias='denyRead')
                                  

                                  Paths where subprocesses are explicitly denied read access. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation

                                  deny_write class-attribute instance-attribute

                                  deny_write: list[DenyWriteItem] | None = Field(None, alias='denyWrite')
                                  

                                  Paths where subprocesses are explicitly denied write access. Takes precedence over allowWrite. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation

                                  disabled class-attribute instance-attribute

                                  disabled: bool | None = False
                                  

                                  Skip filesystem isolation while keeping network isolation: sandboxed commands get unrestricted read and write access to the host filesystem, and network egress stays confined to network.allowedDomains. Only honored from user, managed, or CLI --settings settings (default: false). Requires Claude Code v2.1.216 or later. See https://code.claude.com/docs/en/sandboxing#disable-filesystem-isolation

                                  FromPR dataclass

                                  Bases: BaseSessionConfig

                                  Resume sessions linked to a specific GitHub PR.

                                  Accepts a PR number or URL. Sessions are automatically linked when created via gh pr create.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  @dataclass(kw_only=True)
                                  class FromPR(BaseSessionConfig):
                                      """Resume sessions linked to a specific GitHub PR.
                                  
                                      Accepts a PR number or URL. Sessions are automatically linked
                                      when created via ``gh pr create``.
                                      """
                                  
                                      mode: Literal["from_pr"] = "from_pr"
                                      pr: int | str
                                      """PR number or URL."""
                                      fork: bool = False
                                      """If True, fork to a new session ID instead of continuing in-place."""
                                  

                                  fork class-attribute instance-attribute

                                  fork: bool = False
                                  

                                  If True, fork to a new session ID instead of continuing in-place.

                                  pr instance-attribute

                                  pr: int | str
                                  

                                  PR number or URL.

                                  GetSettingsResponse

                                  Bases: BaseModel

                                  Response from get_settings() containing effective and per-source settings.

                                  Source code in src/clawd_code_sdk/models/control.py
                                  class GetSettingsResponse(BaseModel):
                                      """Response from get_settings() containing effective and per-source settings."""
                                  
                                      effective: dict[str, Any]
                                      """The merged effective settings (ClaudeCodeSettings shape, camelCase keys)."""
                                  
                                      sources: list[SettingsSource]
                                      """Raw settings from each source."""
                                  
                                      applied: AppliedSettings
                                      """The currently applied model and effort."""
                                  

                                  applied instance-attribute

                                  applied: AppliedSettings
                                  

                                  The currently applied model and effort.

                                  effective instance-attribute

                                  effective: dict[str, Any]
                                  

                                  The merged effective settings (ClaudeCodeSettings shape, camelCase keys).

                                  sources instance-attribute

                                  sources: list[SettingsSource]
                                  

                                  Raw settings from each source.

                                  HookContext

                                  Bases: TypedDict

                                  Context information for hook callbacks.

                                  Fields

                                  signal: Reserved for future abort signal support. Currently always None.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class HookContext(TypedDict):
                                      """Context information for hook callbacks.
                                  
                                      Fields:
                                          signal: Reserved for future abort signal support. Currently always None.
                                      """
                                  
                                      signal: Any | None  # Future: abort signal support
                                  

                                  HookMatcher

                                  Bases: BaseModel

                                  Hook matcher configuration.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class HookMatcher(BaseModel):
                                      """Hook matcher configuration."""
                                  
                                      # See https://docs.anthropic.com/en/docs/claude-code/hooks#structure for the
                                      # expected string value. For example, for PreToolUse, the matcher can be
                                      # a tool name like "Bash" or a combination of tool names like
                                      # "Write|MultiEdit|Edit".
                                      matcher: str | None = None
                                      # A list of Python functions with function signature HookCallback
                                      hooks: Sequence[HookCallback] = field(default_factory=list)
                                      # Timeout in seconds for all hooks in this matcher (default: 60)
                                      timeout: float | None = None
                                      on_failure: Literal["continue", "block"] | None = None
                                      """What to do when a hook callback fails (raises, times out).
                                  
                                      ``"continue"`` ignores the failure, ``"block"`` fails closed and blocks the action.
                                      Requires a CLI that reports ``hook_on_failure_supported``.
                                      """
                                  

                                  on_failure class-attribute instance-attribute

                                  on_failure: Literal['continue', 'block'] | None = None
                                  

                                  What to do when a hook callback fails (raises, times out).

                                  "continue" ignores the failure, "block" fails closed and blocks the action. Requires a CLI that reports hook_on_failure_supported.

                                  HookMatcherConfig

                                  Bases: TypedDict

                                  Declarative hook matcher for agent/skill/settings hook configuration.

                                  See https://code.claude.com/docs/en/hooks#matcher-patterns

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class HookMatcherConfig(TypedDict):
                                      """Declarative hook matcher for agent/skill/settings hook configuration.
                                  
                                      See https://code.claude.com/docs/en/hooks#matcher-patterns
                                      """
                                  
                                      matcher: NotRequired[str | None]
                                      hooks: list[HookHandler]
                                  

                                  Hooks

                                  Bases: ClaudeCodeBaseModel

                                  Lifecycle event hooks that run at configurable points during Claude Code operation (tool use, session start/end, notifications, prompt submit, message display, and more), not just before/after tool executions. See https://code.claude.com/docs/en/hooks.

                                  Source code in src/clawd_code_sdk/models/settings.py
                                  class Hooks(ClaudeCodeBaseModel):
                                      """Lifecycle event hooks that run at configurable points during Claude Code operation (tool use, session start/end, notifications, prompt submit, message display, and more), not just before/after tool executions. See https://code.claude.com/docs/en/hooks."""
                                  
                                      model_config = ConfigDict(
                                          extra="forbid",
                                      )
                                      pre_tool_use: list[HookMatcher] | None = Field(None, alias="PreToolUse")
                                      """
                                      Hooks that run before tool calls
                                      """
                                      post_tool_use: list[HookMatcher] | None = Field(None, alias="PostToolUse")
                                      """
                                      Hooks that run after tool completion
                                      """
                                      post_tool_use_failure: list[HookMatcher] | None = Field(None, alias="PostToolUseFailure")
                                      """
                                      Hooks that run after a tool fails
                                      """
                                      permission_request: list[HookMatcher] | None = Field(None, alias="PermissionRequest")
                                      """
                                      Hooks that run when a permission dialog appears
                                      """
                                      notification: list[HookMatcher] | None = Field(None, alias="Notification")
                                      """
                                      Hooks that trigger on notifications
                                      """
                                      user_prompt_submit: list[HookMatcher] | None = Field(None, alias="UserPromptSubmit")
                                      """
                                      Hooks that run when a user submits a prompt
                                      """
                                      stop: list[HookMatcher] | None = Field(None, alias="Stop")
                                      """
                                      Hooks that run when agents finish responding. Does not run on user interrupt
                                      """
                                      stop_failure: list[HookMatcher] | None = Field(None, alias="StopFailure")
                                      """
                                      Hooks that run when a turn ends due to an API error (e.g., rate_limit, authentication_failed, billing_error, invalid_request, server_error, max_output_tokens, unknown). Matcher can scope to specific error types. Hook output and exit code are ignored. See https://code.claude.com/docs/en/hooks
                                      """
                                      subagent_start: list[HookMatcher] | None = Field(None, alias="SubagentStart")
                                      """
                                      Hooks that run when a subagent is spawned
                                      """
                                      subagent_stop: list[HookMatcher] | None = Field(None, alias="SubagentStop")
                                      """
                                      Hooks that run when subagents finish responding
                                      """
                                      pre_compact: list[HookMatcher] | None = Field(None, alias="PreCompact")
                                      """
                                      Hooks that run before the context is compacted
                                      """
                                      post_compact: list[HookMatcher] | None = Field(None, alias="PostCompact")
                                      """
                                      Hooks that run after the context is compacted. See https://code.claude.com/docs/en/hooks
                                      """
                                      elicitation: list[HookMatcher] | None = Field(None, alias="Elicitation")
                                      """
                                      Hooks that run when an MCP server requests user input during a tool call. See https://code.claude.com/docs/en/hooks
                                      """
                                      elicitation_result: list[HookMatcher] | None = Field(None, alias="ElicitationResult")
                                      """
                                      Hooks that run after a user responds to an MCP elicitation, before the response is sent back to the server. See https://code.claude.com/docs/en/hooks
                                      """
                                      teammate_idle: list[HookMatcher] | None = Field(None, alias="TeammateIdle")
                                      """
                                      Hooks that run when an agent team teammate is about to go idle. Exit code 2 sends feedback and keeps the teammate working. Does not support matchers. Agent teams are experimental. See https://code.claude.com/docs/en/hooks#teammateidle
                                      """
                                      task_completed: list[HookMatcher] | None = Field(None, alias="TaskCompleted")
                                      """
                                      Hooks that run when a task is being marked as completed. Exit code 2 prevents completion and sends feedback. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcompleted
                                      """
                                      setup: list[HookMatcher] | None = Field(None, alias="Setup")
                                      """
                                      UNDOCUMENTED. Hooks that run during repository initialization (--init, --init-only) or maintenance (--maintenance)
                                      """
                                      instructions_loaded: list[HookMatcher] | None = Field(None, alias="InstructionsLoaded")
                                      """
                                      Hooks that run when a CLAUDE.md or .claude/rules/*.md file is loaded into context. Fires at session start and when files are lazily loaded (e.g., nested traversal, path glob match). No decision control; used for audit logging and observability. Does not support matchers. See https://code.claude.com/docs/en/hooks#instructionsloaded
                                      """
                                      cwd_changed: list[HookMatcher] | None = Field(None, alias="CwdChanged")
                                      """
                                      Hooks that run when the working directory changes. Provides cwd (new directory) and previous_cwd. Matchers are ignored; fires on every directory change. See https://code.claude.com/docs/en/hooks#cwdchanged
                                      """
                                      file_changed: list[HookMatcher] | None = Field(None, alias="FileChanged")
                                      """
                                      Hooks that run when a watched file is created, modified, or deleted. Supports filename matchers. Provides file_path and file_event_type (created, modified, deleted). See https://code.claude.com/docs/en/hooks#filechanged
                                      """
                                      config_change: list[HookMatcher] | None = Field(None, alias="ConfigChange")
                                      """
                                      Hooks that run when settings, managed settings, or skill files change during a session. Supports matchers: user_settings, project_settings, local_settings, policy_settings, skills. Command handlers only. Exit code 2 blocks the change (except policy_settings which is audit-only). See https://code.claude.com/docs/en/hooks#configchange
                                      """
                                      worktree_create: list[HookMatcher] | None = Field(None, alias="WorktreeCreate")
                                      """
                                      Hooks that run when a worktree is created via --worktree or isolation: "worktree" in subagents. Command handlers only, no matchers. Hook must print absolute path to created worktree on stdout; non-zero exit fails creation. See https://code.claude.com/docs/en/hooks#worktreecreate
                                      """
                                      worktree_remove: list[HookMatcher] | None = Field(None, alias="WorktreeRemove")
                                      """
                                      Hooks that run when a worktree is being removed at session exit or when a subagent finishes. Command handlers only, no matchers. Used for cleanup tasks; cannot block removal. See https://code.claude.com/docs/en/hooks#worktreeremove
                                      """
                                      session_start: list[HookMatcher] | None = Field(None, alias="SessionStart")
                                      """
                                      Hooks that run when a new session starts
                                      """
                                      session_end: list[HookMatcher] | None = Field(None, alias="SessionEnd")
                                      """
                                      Hooks that run when a session ends
                                      """
                                      post_tool_batch: list[HookMatcher] | None = Field(None, alias="PostToolBatch")
                                      """
                                      Hooks that run after a full batch of parallel tool calls resolves, before the next model call. Exit code 2 blocks the agentic loop. Does not support matchers. See https://code.claude.com/docs/en/hooks
                                      """
                                      task_created: list[HookMatcher] | None = Field(None, alias="TaskCreated")
                                      """
                                      Hooks that run when a task is being created via TaskCreate. Exit code 2 rolls back task creation. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcreated
                                      """
                                      permission_denied: list[HookMatcher] | None = Field(None, alias="PermissionDenied")
                                      """
                                      Hooks that run when a tool call is denied by the auto mode classifier. Supports matchers on tool name. See https://code.claude.com/docs/en/hooks
                                      """
                                      user_prompt_expansion: list[HookMatcher] | None = Field(None, alias="UserPromptExpansion")
                                      """
                                      Hooks that run when a user-typed command expands into a prompt, before it reaches Claude. Exit code 2 blocks the expansion. Supports matchers on command name. See https://code.claude.com/docs/en/hooks
                                      """
                                      message_display: list[HookMatcher] | None = Field(None, alias="MessageDisplay")
                                      """
                                      Hooks that run while assistant message text is displayed
                                      """
                                      directory_added: list[HookMatcher] | None = Field(None, alias="DirectoryAdded")
                                      """
                                      UNDOCUMENTED. Hooks that run after /add-dir or the SDK register_repo_root control request registers a new working directory mid-session (added v2.1.219)
                                      """
                                  

                                  config_change class-attribute instance-attribute

                                  config_change: list[HookMatcher] | None = Field(None, alias='ConfigChange')
                                  

                                  Hooks that run when settings, managed settings, or skill files change during a session. Supports matchers: user_settings, project_settings, local_settings, policy_settings, skills. Command handlers only. Exit code 2 blocks the change (except policy_settings which is audit-only). See https://code.claude.com/docs/en/hooks#configchange

                                  cwd_changed class-attribute instance-attribute

                                  cwd_changed: list[HookMatcher] | None = Field(None, alias='CwdChanged')
                                  

                                  Hooks that run when the working directory changes. Provides cwd (new directory) and previous_cwd. Matchers are ignored; fires on every directory change. See https://code.claude.com/docs/en/hooks#cwdchanged

                                  directory_added class-attribute instance-attribute

                                  directory_added: list[HookMatcher] | None = Field(None, alias='DirectoryAdded')
                                  

                                  UNDOCUMENTED. Hooks that run after /add-dir or the SDK register_repo_root control request registers a new working directory mid-session (added v2.1.219)

                                  elicitation class-attribute instance-attribute

                                  elicitation: list[HookMatcher] | None = Field(None, alias='Elicitation')
                                  

                                  Hooks that run when an MCP server requests user input during a tool call. See https://code.claude.com/docs/en/hooks

                                  elicitation_result class-attribute instance-attribute

                                  elicitation_result: list[HookMatcher] | None = Field(None, alias='ElicitationResult')
                                  

                                  Hooks that run after a user responds to an MCP elicitation, before the response is sent back to the server. See https://code.claude.com/docs/en/hooks

                                  file_changed class-attribute instance-attribute

                                  file_changed: list[HookMatcher] | None = Field(None, alias='FileChanged')
                                  

                                  Hooks that run when a watched file is created, modified, or deleted. Supports filename matchers. Provides file_path and file_event_type (created, modified, deleted). See https://code.claude.com/docs/en/hooks#filechanged

                                  instructions_loaded class-attribute instance-attribute

                                  instructions_loaded: list[HookMatcher] | None = Field(None, alias='InstructionsLoaded')
                                  

                                  Hooks that run when a CLAUDE.md or .claude/rules/*.md file is loaded into context. Fires at session start and when files are lazily loaded (e.g., nested traversal, path glob match). No decision control; used for audit logging and observability. Does not support matchers. See https://code.claude.com/docs/en/hooks#instructionsloaded

                                  message_display class-attribute instance-attribute

                                  message_display: list[HookMatcher] | None = Field(None, alias='MessageDisplay')
                                  

                                  Hooks that run while assistant message text is displayed

                                  notification class-attribute instance-attribute

                                  notification: list[HookMatcher] | None = Field(None, alias='Notification')
                                  

                                  Hooks that trigger on notifications

                                  permission_denied class-attribute instance-attribute

                                  permission_denied: list[HookMatcher] | None = Field(None, alias='PermissionDenied')
                                  

                                  Hooks that run when a tool call is denied by the auto mode classifier. Supports matchers on tool name. See https://code.claude.com/docs/en/hooks

                                  permission_request class-attribute instance-attribute

                                  permission_request: list[HookMatcher] | None = Field(None, alias='PermissionRequest')
                                  

                                  Hooks that run when a permission dialog appears

                                  post_compact class-attribute instance-attribute

                                  post_compact: list[HookMatcher] | None = Field(None, alias='PostCompact')
                                  

                                  Hooks that run after the context is compacted. See https://code.claude.com/docs/en/hooks

                                  post_tool_batch class-attribute instance-attribute

                                  post_tool_batch: list[HookMatcher] | None = Field(None, alias='PostToolBatch')
                                  

                                  Hooks that run after a full batch of parallel tool calls resolves, before the next model call. Exit code 2 blocks the agentic loop. Does not support matchers. See https://code.claude.com/docs/en/hooks

                                  post_tool_use class-attribute instance-attribute

                                  post_tool_use: list[HookMatcher] | None = Field(None, alias='PostToolUse')
                                  

                                  Hooks that run after tool completion

                                  post_tool_use_failure class-attribute instance-attribute

                                  post_tool_use_failure: list[HookMatcher] | None = Field(None, alias='PostToolUseFailure')
                                  

                                  Hooks that run after a tool fails

                                  pre_compact class-attribute instance-attribute

                                  pre_compact: list[HookMatcher] | None = Field(None, alias='PreCompact')
                                  

                                  Hooks that run before the context is compacted

                                  pre_tool_use class-attribute instance-attribute

                                  pre_tool_use: list[HookMatcher] | None = Field(None, alias='PreToolUse')
                                  

                                  Hooks that run before tool calls

                                  session_end class-attribute instance-attribute

                                  session_end: list[HookMatcher] | None = Field(None, alias='SessionEnd')
                                  

                                  Hooks that run when a session ends

                                  session_start class-attribute instance-attribute

                                  session_start: list[HookMatcher] | None = Field(None, alias='SessionStart')
                                  

                                  Hooks that run when a new session starts

                                  setup class-attribute instance-attribute

                                  setup: list[HookMatcher] | None = Field(None, alias='Setup')
                                  

                                  UNDOCUMENTED. Hooks that run during repository initialization (--init, --init-only) or maintenance (--maintenance)

                                  stop class-attribute instance-attribute

                                  stop: list[HookMatcher] | None = Field(None, alias='Stop')
                                  

                                  Hooks that run when agents finish responding. Does not run on user interrupt

                                  stop_failure class-attribute instance-attribute

                                  stop_failure: list[HookMatcher] | None = Field(None, alias='StopFailure')
                                  

                                  Hooks that run when a turn ends due to an API error (e.g., rate_limit, authentication_failed, billing_error, invalid_request, server_error, max_output_tokens, unknown). Matcher can scope to specific error types. Hook output and exit code are ignored. See https://code.claude.com/docs/en/hooks

                                  subagent_start class-attribute instance-attribute

                                  subagent_start: list[HookMatcher] | None = Field(None, alias='SubagentStart')
                                  

                                  Hooks that run when a subagent is spawned

                                  subagent_stop class-attribute instance-attribute

                                  subagent_stop: list[HookMatcher] | None = Field(None, alias='SubagentStop')
                                  

                                  Hooks that run when subagents finish responding

                                  task_completed class-attribute instance-attribute

                                  task_completed: list[HookMatcher] | None = Field(None, alias='TaskCompleted')
                                  

                                  Hooks that run when a task is being marked as completed. Exit code 2 prevents completion and sends feedback. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcompleted

                                  task_created class-attribute instance-attribute

                                  task_created: list[HookMatcher] | None = Field(None, alias='TaskCreated')
                                  

                                  Hooks that run when a task is being created via TaskCreate. Exit code 2 rolls back task creation. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcreated

                                  teammate_idle class-attribute instance-attribute

                                  teammate_idle: list[HookMatcher] | None = Field(None, alias='TeammateIdle')
                                  

                                  Hooks that run when an agent team teammate is about to go idle. Exit code 2 sends feedback and keeps the teammate working. Does not support matchers. Agent teams are experimental. See https://code.claude.com/docs/en/hooks#teammateidle

                                  user_prompt_expansion class-attribute instance-attribute

                                  user_prompt_expansion: list[HookMatcher] | None = Field(None, alias='UserPromptExpansion')
                                  

                                  Hooks that run when a user-typed command expands into a prompt, before it reaches Claude. Exit code 2 blocks the expansion. Supports matchers on command name. See https://code.claude.com/docs/en/hooks

                                  user_prompt_submit class-attribute instance-attribute

                                  user_prompt_submit: list[HookMatcher] | None = Field(None, alias='UserPromptSubmit')
                                  

                                  Hooks that run when a user submits a prompt

                                  worktree_create class-attribute instance-attribute

                                  worktree_create: list[HookMatcher] | None = Field(None, alias='WorktreeCreate')
                                  

                                  Hooks that run when a worktree is created via --worktree or isolation: "worktree" in subagents. Command handlers only, no matchers. Hook must print absolute path to created worktree on stdout; non-zero exit fails creation. See https://code.claude.com/docs/en/hooks#worktreecreate

                                  worktree_remove class-attribute instance-attribute

                                  worktree_remove: list[HookMatcher] | None = Field(None, alias='WorktreeRemove')
                                  

                                  Hooks that run when a worktree is being removed at session exit or when a subagent finishes. Command handlers only, no matchers. Used for cleanup tasks; cannot block removal. See https://code.claude.com/docs/en/hooks#worktreeremove

                                  ImageBlock

                                  Bases: BaseContentBlock

                                  Image content block (storage-only, not emitted on the wire).

                                  Source code in src/clawd_code_sdk/models/content_blocks.py
                                  class ImageBlock(BaseContentBlock):
                                      """Image content block (storage-only, not emitted on the wire)."""
                                  
                                      type: Literal["image"] = "image"
                                      source: ImageSource
                                  
                                      def to_otel(self) -> BlobPart:
                                          from logfire._internal.integrations.llm_providers.semconv import BlobPart
                                  
                                          return BlobPart(
                                              type="blob",
                                              content=self.source.data,
                                              mime_type=self.source.media_type,
                                              modality="image",
                                          )
                                  

                                  ImageSource

                                  Bases: BaseContentBlock

                                  Base64-encoded image source data.

                                  Source code in src/clawd_code_sdk/models/content_blocks.py
                                  class ImageSource(BaseContentBlock):
                                      """Base64-encoded image source data."""
                                  
                                      type: Literal["base64"] = "base64"
                                      media_type: ImageMediaType
                                      data: str
                                  

                                  InitSystemMessage

                                  Bases: BaseSystemMessage

                                  System init message with session metadata.

                                  Source code in src/clawd_code_sdk/models/system_messages.py
                                  class InitSystemMessage(BaseSystemMessage):
                                      """System init message with session metadata."""
                                  
                                      subtype: Literal["init"] = "init"
                                      api_key_source: ApiKeySource | None = Field(..., validation_alias="apiKeySource")
                                      cwd: str
                                      tools: list[ToolName | str]
                                      mcp_servers: list[McpServerStatus]
                                      model: Model
                                      permission_mode: PermissionMode = Field(..., validation_alias="permissionMode")
                                      slash_commands: list[str]
                                      output_style: Literal["default", "json"] | str  # noqa: PYI051
                                      claude_code_version: str
                                      agents: list[str] | None = None
                                      skills: list[str]
                                      plugins: list[Plugin]
                                      plugin_errors: list[PluginError] | None = None
                                      betas: list[str] | None = None
                                      terminal_slash_commands: list[str] | None = None
                                      fast_mode_state: FastModeState | None = None
                                      """Whether fast mode was enabled."""
                                      fast_mode_disabled_reason: FastModeDisabledReason | None = None
                                      effort: ReasoningEffort | None = None
                                      view_mode: Literal["focus", "default"] | None = None
                                      capabilities: list[str] | None = None
                                      memory_paths: dict[str, str] | None = None
                                      """Auto-memory directories by kind (undocumented)."""
                                      original_cwd: str | None = None
                                      """The cwd the session was started in (undocumented)."""
                                      additional_directories: list[str] | None = None
                                      """Extra working directories added to the session (undocumented)."""
                                      messaging_socket_path: str | None = None
                                      """Path of the CLI's local messaging socket (undocumented)."""
                                      analytics_disabled: bool | None = None
                                      product_feedback_disabled: bool | None = None
                                      per_turn_effort_active: bool | None = None
                                      ultrathink_available: bool | None = None
                                      ultrathink_typed_raises: bool | None = None
                                      served_by_anthropic: bool | None = None
                                      """Whether requests are served by Anthropic directly (undocumented)."""
                                      startup_timing: dict[str, Any] | None = None
                                      """Startup timing diagnostics (undocumented, nested phase timings)."""
                                      user_message_uuids: list[str] | None = None
                                      """Client uuids of the user messages the turn takes in (undocumented, CLI 2.1.330+)."""
                                  

                                  additional_directories class-attribute instance-attribute

                                  additional_directories: list[str] | None = None
                                  

                                  Extra working directories added to the session (undocumented).

                                  fast_mode_state class-attribute instance-attribute

                                  fast_mode_state: FastModeState | None = None
                                  

                                  Whether fast mode was enabled.

                                  memory_paths class-attribute instance-attribute

                                  memory_paths: dict[str, str] | None = None
                                  

                                  Auto-memory directories by kind (undocumented).

                                  messaging_socket_path class-attribute instance-attribute

                                  messaging_socket_path: str | None = None
                                  

                                  Path of the CLI's local messaging socket (undocumented).

                                  original_cwd class-attribute instance-attribute

                                  original_cwd: str | None = None
                                  

                                  The cwd the session was started in (undocumented).

                                  served_by_anthropic class-attribute instance-attribute

                                  served_by_anthropic: bool | None = None
                                  

                                  Whether requests are served by Anthropic directly (undocumented).

                                  startup_timing class-attribute instance-attribute

                                  startup_timing: dict[str, Any] | None = None
                                  

                                  Startup timing diagnostics (undocumented, nested phase timings).

                                  user_message_uuids class-attribute instance-attribute

                                  user_message_uuids: list[str] | None = None
                                  

                                  Client uuids of the user messages the turn takes in (undocumented, CLI 2.1.330+).

                                  InvalidRequestError

                                  Bases: APIError

                                  Raised when the API request is invalid (400).

                                  This may indicate invalid parameters, unsupported model, or malformed input. Check the error message for details about what needs to be corrected.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class InvalidRequestError(APIError):
                                      """Raised when the API request is invalid (400).
                                  
                                      This may indicate invalid parameters, unsupported model, or malformed input.
                                      Check the error message for details about what needs to be corrected.
                                      """
                                  
                                      def __init__(self, message: str, model: Model | None = None) -> None:
                                          super().__init__(message, "invalid_request", model)
                                  

                                  McpAuthenticateResponse

                                  Bases: ClaudeCodeBaseModel

                                  Response from authenticating with an MCP server.

                                  Source code in src/clawd_code_sdk/models/control.py
                                  class McpAuthenticateResponse(ClaudeCodeBaseModel):
                                      """Response from authenticating with an MCP server."""
                                  
                                      auth_url: str | None = None
                                      """OAuth authorization URL for the user to visit, if user action is required."""
                                  
                                      requires_user_action: bool
                                      """Whether the user needs to complete an OAuth flow in the browser."""
                                  

                                  auth_url class-attribute instance-attribute

                                  auth_url: str | None = None
                                  

                                  OAuth authorization URL for the user to visit, if user action is required.

                                  requires_user_action instance-attribute

                                  requires_user_action: bool
                                  

                                  Whether the user needs to complete an OAuth flow in the browser.

                                  McpSdkServerConfig dataclass

                                  SDK MCP server configuration (serializable, no instance).

                                  Source code in src/clawd_code_sdk/models/mcp.py
                                  @dataclass(kw_only=True)
                                  class McpSdkServerConfig:
                                      """SDK MCP server configuration (serializable, no instance)."""
                                  
                                      type: Literal["sdk"] = "sdk"
                                      name: str
                                      timeout: float | None = None
                                      """Per-request timeout for this server in milliseconds."""
                                      tools: list[McpServerToolPolicy] | None = None
                                  

                                  timeout class-attribute instance-attribute

                                  timeout: float | None = None
                                  

                                  Per-request timeout for this server in milliseconds.

                                  McpSdkServerConfigWithInstance dataclass

                                  Bases: McpSdkServerConfig

                                  SDK MCP server config with a live McpServer instance. Not serializable.

                                  Source code in src/clawd_code_sdk/models/mcp.py
                                  @dataclass(kw_only=True)
                                  class McpSdkServerConfigWithInstance(McpSdkServerConfig):
                                      """SDK MCP server config with a live McpServer instance. Not serializable."""
                                  
                                      instance: McpServer = field(repr=False)
                                  

                                  McpSetServersResult

                                  Bases: ClaudeCodeBaseModel

                                  Result of a setMcpServers operation.

                                  Source code in src/clawd_code_sdk/models/mcp.py
                                  class McpSetServersResult(ClaudeCodeBaseModel):
                                      """Result of a setMcpServers operation."""
                                  
                                      added: list[str] = Field(default_factory=list)
                                      removed: list[str] = Field(default_factory=list)
                                      errors: dict[str, str] = Field(default_factory=dict)
                                  

                                  Network

                                  Bases: ClaudeCodeBaseModel

                                  Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.

                                  Source code in src/clawd_code_sdk/models/settings.py
                                  class Network(ClaudeCodeBaseModel):
                                      """Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration."""
                                  
                                      model_config = ConfigDict(
                                          extra="forbid",
                                      )
                                      allow_unix_sockets: list[str] | None = Field(None, alias="allowUnixSockets")
                                      """
                                      Allow Unix domain sockets for local IPC (SSH agent, Docker, etc.). Provide an array of specific paths. Defaults to blocking if not specified. See https://code.claude.com/docs/en/sandboxing#network-isolation
                                      """
                                      allow_local_binding: bool | None = Field(None, alias="allowLocalBinding")
                                      """
                                      Allow binding to local network addresses (e.g., localhost ports). Defaults to false if not specified. See https://code.claude.com/docs/en/sandboxing#network-isolation
                                      """
                                      http_proxy_port: int | None = Field(None, alias="httpProxyPort", ge=1, le=65535)
                                      """
                                      HTTP proxy port to use for network filtering. If not specified, a proxy server will be started automatically. See https://code.claude.com/docs/en/sandboxing#custom-proxy-configuration
                                      """
                                      socks_proxy_port: int | None = Field(None, alias="socksProxyPort", ge=1, le=65535)
                                      """
                                      SOCKS proxy port to use for network filtering. If not specified, a proxy server will be started automatically. See https://code.claude.com/docs/en/sandboxing#custom-proxy-configuration
                                      """
                                      allow_all_unix_sockets: bool | None = Field(None, alias="allowAllUnixSockets")
                                      """
                                      Allow all Unix domain socket connections. If true, this overrides allowUnixSockets. See https://code.claude.com/docs/en/sandboxing#network-isolation
                                      """
                                      allowed_domains: list[AllowedDomain] | None = Field(None, alias="allowedDomains")
                                      """
                                      Allowlist of network domains for sandboxed commands. Supports wildcard patterns like *.example.com. See https://code.claude.com/docs/en/sandboxing#network-isolation
                                      """
                                      denied_domains: list[DeniedDomain] | None = Field(None, alias="deniedDomains")
                                      """
                                      Blocklist of network domains for sandboxed commands. Blocks specific domains even when a broader allowedDomains wildcard would otherwise permit them. Supports wildcard patterns like *.example.com. See https://code.claude.com/docs/en/sandboxing#network-isolation
                                      """
                                      allow_managed_domains_only: bool | None = Field(None, alias="allowManagedDomainsOnly")
                                      """
                                      (Managed settings only) Only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources. Non-allowed domains are automatically blocked without user prompts. See https://code.claude.com/docs/en/sandboxing#network-isolation
                                      """
                                      allow_mach_lookup: list[AllowMachLookupItem] | None = Field(
                                          None, alias="allowMachLookup", examples=[["com.apple.coresimulator.*"]]
                                      )
                                      """
                                      macOS only. Additional XPC/Mach service names the sandbox may look up. Supports a single trailing * for prefix matching. Needed for tools that communicate via XPC such as the iOS Simulator or Playwright. See https://code.claude.com/docs/en/sandboxing#network-isolation
                                      """
                                      tls_terminate: TlsTerminate | None = Field(None, alias="tlsTerminate")
                                      """
                                      Experimental. Terminate TLS inside the sandbox proxy so it can read the contents of HTTPS requests. Required for mask credential substitution. Set {} to generate an ephemeral certificate authority for the session, or set caCertPath and caKeyPath to use your own. Only honored from user, managed, or CLI --settings settings, not from .claude/settings.json or .claude/settings.local.json. Requires Claude Code v2.1.199 or later. See https://code.claude.com/docs/en/sandboxing#protect-credentials
                                      """
                                      strict_allowlist: bool | None = Field(None, alias="strictAllowlist")
                                      """
                                      UNDOCUMENTED. Deny non-allowlisted hosts for sandboxed commands without prompting (added v2.1.219). See https://code.claude.com/docs/en/sandboxing#network-isolation
                                      """
                                  

                                  allow_all_unix_sockets class-attribute instance-attribute

                                  allow_all_unix_sockets: bool | None = Field(None, alias='allowAllUnixSockets')
                                  

                                  Allow all Unix domain socket connections. If true, this overrides allowUnixSockets. See https://code.claude.com/docs/en/sandboxing#network-isolation

                                  allow_local_binding class-attribute instance-attribute

                                  allow_local_binding: bool | None = Field(None, alias='allowLocalBinding')
                                  

                                  Allow binding to local network addresses (e.g., localhost ports). Defaults to false if not specified. See https://code.claude.com/docs/en/sandboxing#network-isolation

                                  allow_mach_lookup class-attribute instance-attribute

                                  allow_mach_lookup: list[AllowMachLookupItem] | None = Field(
                                      None, alias="allowMachLookup", examples=[["com.apple.coresimulator.*"]]
                                  )
                                  

                                  macOS only. Additional XPC/Mach service names the sandbox may look up. Supports a single trailing * for prefix matching. Needed for tools that communicate via XPC such as the iOS Simulator or Playwright. See https://code.claude.com/docs/en/sandboxing#network-isolation

                                  allow_managed_domains_only class-attribute instance-attribute

                                  allow_managed_domains_only: bool | None = Field(None, alias='allowManagedDomainsOnly')
                                  

                                  (Managed settings only) Only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources. Non-allowed domains are automatically blocked without user prompts. See https://code.claude.com/docs/en/sandboxing#network-isolation

                                  allow_unix_sockets class-attribute instance-attribute

                                  allow_unix_sockets: list[str] | None = Field(None, alias='allowUnixSockets')
                                  

                                  Allow Unix domain sockets for local IPC (SSH agent, Docker, etc.). Provide an array of specific paths. Defaults to blocking if not specified. See https://code.claude.com/docs/en/sandboxing#network-isolation

                                  allowed_domains class-attribute instance-attribute

                                  allowed_domains: list[AllowedDomain] | None = Field(None, alias='allowedDomains')
                                  

                                  Allowlist of network domains for sandboxed commands. Supports wildcard patterns like *.example.com. See https://code.claude.com/docs/en/sandboxing#network-isolation

                                  denied_domains class-attribute instance-attribute

                                  denied_domains: list[DeniedDomain] | None = Field(None, alias='deniedDomains')
                                  

                                  Blocklist of network domains for sandboxed commands. Blocks specific domains even when a broader allowedDomains wildcard would otherwise permit them. Supports wildcard patterns like *.example.com. See https://code.claude.com/docs/en/sandboxing#network-isolation

                                  http_proxy_port class-attribute instance-attribute

                                  http_proxy_port: int | None = Field(None, alias='httpProxyPort', ge=1, le=65535)
                                  

                                  HTTP proxy port to use for network filtering. If not specified, a proxy server will be started automatically. See https://code.claude.com/docs/en/sandboxing#custom-proxy-configuration

                                  socks_proxy_port class-attribute instance-attribute

                                  socks_proxy_port: int | None = Field(None, alias='socksProxyPort', ge=1, le=65535)
                                  

                                  SOCKS proxy port to use for network filtering. If not specified, a proxy server will be started automatically. See https://code.claude.com/docs/en/sandboxing#custom-proxy-configuration

                                  strict_allowlist class-attribute instance-attribute

                                  strict_allowlist: bool | None = Field(None, alias='strictAllowlist')
                                  

                                  UNDOCUMENTED. Deny non-allowlisted hosts for sandboxed commands without prompting (added v2.1.219). See https://code.claude.com/docs/en/sandboxing#network-isolation

                                  tls_terminate class-attribute instance-attribute

                                  tls_terminate: TlsTerminate | None = Field(None, alias='tlsTerminate')
                                  

                                  Experimental. Terminate TLS inside the sandbox proxy so it can read the contents of HTTPS requests. Required for mask credential substitution. Set {} to generate an ephemeral certificate authority for the session, or set caCertPath and caKeyPath to use your own. Only honored from user, managed, or CLI --settings settings, not from .claude/settings.json or .claude/settings.local.json. Requires Claude Code v2.1.199 or later. See https://code.claude.com/docs/en/sandboxing#protect-credentials

                                  NewSession dataclass

                                  Bases: BaseSessionConfig

                                  Start a fresh session.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  @dataclass(kw_only=True)
                                  class NewSession(BaseSessionConfig):
                                      """Start a fresh session."""
                                  
                                      mode: Literal["new"] = "new"
                                      session_id: str | None = None
                                      """Deterministic session ID, or None to auto-generate a UUID."""
                                      title: str | None = None
                                      """Title for the session, or None to auto-generate a title."""
                                  

                                  session_id class-attribute instance-attribute

                                  session_id: str | None = None
                                  

                                  Deterministic session ID, or None to auto-generate a UUID.

                                  title class-attribute instance-attribute

                                  title: str | None = None
                                  

                                  Title for the session, or None to auto-generate a title.

                                  NotificationHookInput

                                  Bases: BaseHookInput

                                  Input data for Notification hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class NotificationHookInput(BaseHookInput):
                                      """Input data for Notification hook events."""
                                  
                                      hook_event_name: Literal["Notification"]
                                      message: str
                                      title: NotRequired[str]
                                      notification_type: str
                                  

                                  NotificationHookSpecificOutput

                                  Bases: TypedDict

                                  Hook-specific output for Notification events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class NotificationHookSpecificOutput(TypedDict):
                                      """Hook-specific output for Notification events."""
                                  
                                      hookEventName: Literal["Notification"]
                                      additionalContext: NotRequired[str]
                                  

                                  PermissionRequestHookInput

                                  Bases: BaseHookInput

                                  Input data for PermissionRequest hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class PermissionRequestHookInput(BaseHookInput):
                                      """Input data for PermissionRequest hook events."""
                                  
                                      hook_event_name: Literal["PermissionRequest"]
                                      tool_name: str
                                      tool_input: dict[str, Any]
                                      permission_suggestions: NotRequired[list[PermissionUpdate]]
                                      mcp_server: NotRequired[McpServerProvenance]
                                      agent_id: NotRequired[str]
                                      agent_type: NotRequired[str]
                                  

                                  PermissionRequestHookSpecificOutput

                                  Bases: TypedDict

                                  Hook-specific output for PermissionRequest events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class PermissionRequestHookSpecificOutput(TypedDict):
                                      """Hook-specific output for PermissionRequest events."""
                                  
                                      hookEventName: Literal["PermissionRequest"]
                                      decision: dict[str, Any]
                                  

                                  PermissionResultAllow

                                  Bases: ClaudeCodeBaseModel

                                  Allow permission result.

                                  Source code in src/clawd_code_sdk/models/permissions.py
                                  class PermissionResultAllow(ClaudeCodeBaseModel):
                                      """Allow permission result."""
                                  
                                      behavior: Literal["allow"] = "allow"
                                      updated_input: dict[str, Any] | None = None
                                      updated_permissions: list[PermissionUpdate] | None = None
                                      decision_classification: PermissionDecisionClassification | None = None
                                  

                                  PermissionResultDeny

                                  Bases: ClaudeCodeBaseModel

                                  Deny permission result.

                                  Source code in src/clawd_code_sdk/models/permissions.py
                                  class PermissionResultDeny(ClaudeCodeBaseModel):
                                      """Deny permission result."""
                                  
                                      behavior: Literal["deny"] = "deny"
                                      message: str = ""
                                      interrupt: bool = False
                                      decision_classification: PermissionDecisionClassification | None = None
                                  

                                  Permissions

                                  Bases: ClaudeCodeBaseModel

                                  Tool usage permissions configuration. See https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings See https://code.claude.com/docs/en/tools-reference for full list of tools available to Claude.

                                  Source code in src/clawd_code_sdk/models/settings.py
                                  class Permissions(ClaudeCodeBaseModel):
                                      """Tool usage permissions configuration.
                                      See https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings
                                      See https://code.claude.com/docs/en/tools-reference for full list of tools available to Claude.
                                      """
                                  
                                      model_config = ConfigDict(
                                          extra="forbid",
                                      )
                                      allow: list[PermissionRule] | None = None
                                      """
                                      List of permission rules for allowed operations
                                      """
                                      deny: list[PermissionRule] | None = None
                                      """
                                      List of permission rules for denied operations
                                      """
                                      ask: list[PermissionRule] | None = None
                                      """
                                      List of permission rules that should always prompt for confirmation
                                      """
                                      default_mode: (
                                          Literal[
                                              "acceptEdits",
                                              "bypassPermissions",
                                              "default",
                                              "delegate",
                                              "dontAsk",
                                              "plan",
                                              "auto",
                                              "manual",
                                          ]
                                          | None
                                      ) = Field(None, alias="defaultMode")
                                      """
                                      Default permission mode.
                                      "default": prompts on first use.
                                      UNDOCUMENTED. "manual": accepted alias for "default" (the CLI/VS Code/JetBrains UI now labels this mode "Manual" as of v2.1.200; permission-modes.md has not yet been updated to mention it).
                                      "acceptEdits": auto-accepts file edits.
                                      "plan": read-only, no modifications.
                                      UNDOCUMENTED. "delegate": coordination-only for agent team leads (agent teams are experimental; enable via CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS).
                                      "dontAsk": auto-denies unless pre-approved via permissions.
                                      "bypassPermissions": skips all prompts (use only in isolated environments).
                                      "auto": auto-approves tool calls with background safety checks that verify actions align with your request.
                                      See https://code.claude.com/docs/en/permissions
                                      """
                                      disable_bypass_permissions_mode: Literal["disable"] | None = Field(
                                          None, alias="disableBypassPermissionsMode"
                                      )
                                      """
                                      Disable the ability to bypass permission prompts
                                      """
                                      disable_auto_mode: Literal["disable"] | None = Field(None, alias="disableAutoMode")
                                      """
                                      Set to "disable" to prevent auto mode from being activated. Removes `auto` from the Shift+Tab cycle and rejects `--permission-mode auto` at startup. Most useful in managed settings where users cannot override it. See https://code.claude.com/docs/en/permissions
                                      """
                                      block_writes_outside_working_directories: bool | None = Field(
                                          None, alias="blockWritesOutsideWorkingDirectories"
                                      )
                                      """
                                      When true, the Write, Edit, and NotebookEdit tools refuse paths outside the working directories in every permission mode, including bypassPermissions, apart from some of Claude Code's own files. Does not limit shell commands, MCP tools, or the programs hooks run; use sandboxing for those. A true in any settings file applies; false is the same as unset. Requires Claude Code v2.1.314 or later. See https://code.claude.com/docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories
                                      """
                                      additional_directories: list[AdditionalDirectory] | None = Field(
                                          None, alias="additionalDirectories", examples=[["//Users/alice/Documents", "~/projects"]]
                                      )
                                      """
                                      Additional directories to include in the permission scope
                                      """
                                  

                                  additional_directories class-attribute instance-attribute

                                  additional_directories: list[AdditionalDirectory] | None = Field(
                                      None, alias="additionalDirectories", examples=[["//Users/alice/Documents", "~/projects"]]
                                  )
                                  

                                  Additional directories to include in the permission scope

                                  allow class-attribute instance-attribute

                                  allow: list[PermissionRule] | None = None
                                  

                                  List of permission rules for allowed operations

                                  ask class-attribute instance-attribute

                                  ask: list[PermissionRule] | None = None
                                  

                                  List of permission rules that should always prompt for confirmation

                                  block_writes_outside_working_directories class-attribute instance-attribute

                                  block_writes_outside_working_directories: bool | None = Field(
                                      None, alias="blockWritesOutsideWorkingDirectories"
                                  )
                                  

                                  When true, the Write, Edit, and NotebookEdit tools refuse paths outside the working directories in every permission mode, including bypassPermissions, apart from some of Claude Code's own files. Does not limit shell commands, MCP tools, or the programs hooks run; use sandboxing for those. A true in any settings file applies; false is the same as unset. Requires Claude Code v2.1.314 or later. See https://code.claude.com/docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories

                                  default_mode class-attribute instance-attribute

                                  default_mode: (
                                      Literal[
                                          "acceptEdits",
                                          "bypassPermissions",
                                          "default",
                                          "delegate",
                                          "dontAsk",
                                          "plan",
                                          "auto",
                                          "manual",
                                      ]
                                      | None
                                  ) = Field(None, alias="defaultMode")
                                  

                                  Default permission mode. "default": prompts on first use. UNDOCUMENTED. "manual": accepted alias for "default" (the CLI/VS Code/JetBrains UI now labels this mode "Manual" as of v2.1.200; permission-modes.md has not yet been updated to mention it). "acceptEdits": auto-accepts file edits. "plan": read-only, no modifications. UNDOCUMENTED. "delegate": coordination-only for agent team leads (agent teams are experimental; enable via CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS). "dontAsk": auto-denies unless pre-approved via permissions. "bypassPermissions": skips all prompts (use only in isolated environments). "auto": auto-approves tool calls with background safety checks that verify actions align with your request. See https://code.claude.com/docs/en/permissions

                                  deny class-attribute instance-attribute

                                  deny: list[PermissionRule] | None = None
                                  

                                  List of permission rules for denied operations

                                  disable_auto_mode class-attribute instance-attribute

                                  disable_auto_mode: Literal['disable'] | None = Field(None, alias='disableAutoMode')
                                  

                                  Set to "disable" to prevent auto mode from being activated. Removes auto from the Shift+Tab cycle and rejects --permission-mode auto at startup. Most useful in managed settings where users cannot override it. See https://code.claude.com/docs/en/permissions

                                  disable_bypass_permissions_mode class-attribute instance-attribute

                                  disable_bypass_permissions_mode: Literal["disable"] | None = Field(
                                      None, alias="disableBypassPermissionsMode"
                                  )
                                  

                                  Disable the ability to bypass permission prompts

                                  PostCompactHookInput

                                  Bases: BaseHookInput

                                  Input data for PostCompact hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class PostCompactHookInput(BaseHookInput):
                                      """Input data for PostCompact hook events."""
                                  
                                      hook_event_name: Literal["PostCompact"]
                                      trigger: CompactionTrigger
                                      compact_summary: str
                                  

                                  PostToolUseFailureHookInput

                                  Bases: BaseHookInput

                                  Input data for PostToolUseFailure hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class PostToolUseFailureHookInput(BaseHookInput):
                                      """Input data for PostToolUseFailure hook events."""
                                  
                                      hook_event_name: Literal["PostToolUseFailure"]
                                      tool_name: str
                                      tool_input: dict[str, Any]
                                      tool_use_id: str
                                      error: str
                                      duration_ms: NotRequired[float]
                                      mcp_server: NotRequired[McpServerProvenance]
                                      is_interrupt: NotRequired[bool]
                                      agent_id: NotRequired[str]
                                      agent_type: NotRequired[str]
                                  

                                  PostToolUseFailureHookSpecificOutput

                                  Bases: TypedDict

                                  Hook-specific output for PostToolUseFailure events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class PostToolUseFailureHookSpecificOutput(TypedDict):
                                      """Hook-specific output for PostToolUseFailure events."""
                                  
                                      hookEventName: Literal["PostToolUseFailure"]
                                      additionalContext: NotRequired[str]
                                  

                                  PostToolUseHookInput

                                  Bases: BaseHookInput

                                  Input data for PostToolUse hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class PostToolUseHookInput(BaseHookInput):
                                      """Input data for PostToolUse hook events."""
                                  
                                      hook_event_name: Literal["PostToolUse"]
                                      tool_name: str
                                      tool_input: dict[str, Any]
                                      tool_response: Any
                                      tool_use_id: str
                                      duration_ms: NotRequired[float]
                                      mcp_server: NotRequired[McpServerProvenance]
                                      agent_id: NotRequired[str]
                                      agent_type: NotRequired[str]
                                  

                                  PreCompactHookInput

                                  Bases: BaseHookInput

                                  Input data for PreCompact hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class PreCompactHookInput(BaseHookInput):
                                      """Input data for PreCompact hook events."""
                                  
                                      hook_event_name: Literal["PreCompact"]
                                      trigger: CompactionTrigger
                                      custom_instructions: str | None
                                  

                                  PreToolUseHookInput

                                  Bases: BaseHookInput

                                  Input data for PreToolUse hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class PreToolUseHookInput(BaseHookInput):
                                      """Input data for PreToolUse hook events."""
                                  
                                      hook_event_name: Literal["PreToolUse"]
                                      tool_name: str
                                      tool_input: dict[str, Any]
                                      tool_use_id: str
                                      mcp_server: NotRequired[McpServerProvenance]
                                      agent_id: NotRequired[str]
                                      agent_type: NotRequired[str]
                                  

                                  ProcessError

                                  Bases: ClaudeSDKError

                                  Raised when the CLI process fails.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class ProcessError(ClaudeSDKError):
                                      """Raised when the CLI process fails."""
                                  
                                      def __init__(
                                          self, message: str, exit_code: int | None = None, stderr: str | None = None
                                      ) -> None:
                                          self.exit_code = exit_code
                                          self.stderr = stderr
                                  
                                          if exit_code is not None:
                                              message = f"{message} (exit code: {exit_code})"
                                          if stderr:
                                              message = f"{message}\nError output: {stderr}"
                                  
                                          super().__init__(message)
                                  

                                  PromptHookHandler

                                  Bases: TypedDict

                                  LLM prompt hook handler.

                                  See https://code.claude.com/docs/en/hooks#prompt-and-agent-hook-fields

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class PromptHookHandler(TypedDict):
                                      """LLM prompt hook handler.
                                  
                                      See https://code.claude.com/docs/en/hooks#prompt-and-agent-hook-fields
                                      """
                                  
                                      type: Literal["prompt"]
                                      prompt: str
                                      model: NotRequired[str]
                                      timeout: NotRequired[float]
                                      statusMessage: NotRequired[str]
                                      once: NotRequired[bool]
                                  

                                  RateLimitError

                                  Bases: APIError

                                  Raised when API rate limits are exceeded (429).

                                  Applications should implement retry logic with exponential backoff when handling this exception.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class RateLimitError(APIError):
                                      """Raised when API rate limits are exceeded (429).
                                  
                                      Applications should implement retry logic with exponential backoff
                                      when handling this exception.
                                      """
                                  
                                      def __init__(self, message: str, model: Model | None = None) -> None:
                                          super().__init__(message, "rate_limit", model)
                                  

                                  RemoteControlResponse

                                  Bases: BaseModel

                                  Response from enabling remote control.

                                  Contains the URLs and identifiers needed for remote clients to connect to the session.

                                  Source code in src/clawd_code_sdk/models/control.py
                                  class RemoteControlResponse(BaseModel):
                                      """Response from enabling remote control.
                                  
                                      Contains the URLs and identifiers needed for remote clients to connect
                                      to the session.
                                      """
                                  
                                      session_url: str
                                      """URL for the remote control session."""
                                  
                                      connect_url: str
                                      """URL for remote clients to connect to the session."""
                                  
                                      environment_id: str
                                      """Identifier for the environment hosting the session."""
                                  

                                  connect_url instance-attribute

                                  connect_url: str
                                  

                                  URL for remote clients to connect to the session.

                                  environment_id instance-attribute

                                  environment_id: str
                                  

                                  Identifier for the environment hosting the session.

                                  session_url instance-attribute

                                  session_url: str
                                  

                                  URL for the remote control session.

                                  ResultError

                                  Bases: ProcessError

                                  The CLI reported an error result and then exited non-zero.

                                  Replaces the bare "exit code 1" ProcessError that follows an is_error result frame (e.g. a refused resume, error_max_turns), so the exception carries what the CLI actually reported. Subclasses ProcessError so existing handlers keep catching it. (Upstream #1198/#1205.)

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class ResultError(ProcessError):
                                      """The CLI reported an error result and then exited non-zero.
                                  
                                      Replaces the bare "exit code 1" ``ProcessError`` that follows an
                                      ``is_error`` result frame (e.g. a refused resume, ``error_max_turns``), so
                                      the exception carries what the CLI actually reported. Subclasses
                                      ``ProcessError`` so existing handlers keep catching it. (Upstream #1198/#1205.)
                                      """
                                  
                                      def __init__(self, message: str, data: dict[str, Any], exit_code: int | None = None) -> None:
                                          self.data = data
                                          super().__init__(message, exit_code=exit_code)
                                  

                                  ResultErrorMessage

                                  Bases: BaseResultMessage

                                  Error result message.

                                  Source code in src/clawd_code_sdk/models/messages.py
                                  class ResultErrorMessage(BaseResultMessage):
                                      """Error result message."""
                                  
                                      subtype: ErrorSubType
                                      errors: list[str] | None = None
                                      startup_failure_reason: StartupFailureReason | None = None
                                      invalid_config_file: InvalidConfigFile | None = None
                                  

                                  ResultSuccessMessage

                                  Bases: BaseResultMessage

                                  Successful result message.

                                  Source code in src/clawd_code_sdk/models/messages.py
                                  class ResultSuccessMessage(BaseResultMessage):
                                      """Successful result message."""
                                  
                                      subtype: Literal["success"] = "success"
                                      result: str | None = None
                                      structured_output: Any = None
                                      deferred_tool_use: SDKDeferredToolUse | None = None
                                      api_error_status: int | None = None
                                      local_command: str | None = None
                                      """Set when the turn was a local slash command (no model call)."""
                                      warm_spare_claimed: bool | None = None
                                      time_origin_ms: float | None = None
                                      time_to_request_ms: float | None = None
                                      time_to_request_from_spawn_ms: float | None = None
                                      request_sent_wall_ms: float | None = None
                                      first_request_input_tokens: int | None = None
                                      """Input tokens (cache reads and writes included) of the model call sent at
                                      ``request_sent_wall_ms``; only with it, and only when above zero (internal, CLI 2.1.330+)."""
                                      first_request_cache_read_input_tokens: int | None = None
                                      """The cache-read part of ``first_request_input_tokens`` (internal, CLI 2.1.330+)."""
                                      ttft_ms: float | None = None
                                      ttft_stream_ms: float | None = None
                                      first_content_frame_ms: float | None = None
                                      first_stream_post_ms: float | None = None
                                      first_stream_post_wall_ms: float | None = None
                                      first_stream_post_queue_wait_ms: float | None = None
                                      first_stream_post_queued_behind: PostQueuedBehind | None = None
                                      first_text_post_ms: float | None = None
                                      first_text_post_wall_ms: float | None = None
                                      first_text_post_queue_wait_ms: float | None = None
                                      first_text_post_queued_behind: PostQueuedBehind | None = None
                                  

                                  first_request_cache_read_input_tokens class-attribute instance-attribute

                                  first_request_cache_read_input_tokens: int | None = None
                                  

                                  The cache-read part of first_request_input_tokens (internal, CLI 2.1.330+).

                                  first_request_input_tokens class-attribute instance-attribute

                                  first_request_input_tokens: int | None = None
                                  

                                  Input tokens (cache reads and writes included) of the model call sent at request_sent_wall_ms; only with it, and only when above zero (internal, CLI 2.1.330+).

                                  local_command class-attribute instance-attribute

                                  local_command: str | None = None
                                  

                                  Set when the turn was a local slash command (no model call).

                                  ResumeSession dataclass

                                  Bases: BaseSessionConfig

                                  Resume an existing session by ID.

                                  Source code in src/clawd_code_sdk/models/options.py
                                  @dataclass(kw_only=True)
                                  class ResumeSession(BaseSessionConfig):
                                      """Resume an existing session by ID."""
                                  
                                      mode: Literal["resume"] = "resume"
                                      session_id: str
                                      """The session ID to resume."""
                                      fork: bool = False
                                      """If True, fork to a new session ID instead of continuing in-place."""
                                      at_message: str | None = None
                                      """Resume from a specific message UUID within the session."""
                                      drops_turn: str | None = None
                                      """Guard for truncating resume (``--resume-drops-turn``).
                                  
                                      Declares the user message UUID of the turn that ``at_message`` is expected to
                                      drop. The CLI refuses the resume if the truncation would discard anything else.
                                      Only meaningful together with ``at_message``.
                                      """
                                  

                                  at_message class-attribute instance-attribute

                                  at_message: str | None = None
                                  

                                  Resume from a specific message UUID within the session.

                                  drops_turn class-attribute instance-attribute

                                  drops_turn: str | None = None
                                  

                                  Guard for truncating resume (--resume-drops-turn).

                                  Declares the user message UUID of the turn that at_message is expected to drop. The CLI refuses the resume if the truncation would discard anything else. Only meaningful together with at_message.

                                  fork class-attribute instance-attribute

                                  fork: bool = False
                                  

                                  If True, fork to a new session ID instead of continuing in-place.

                                  session_id instance-attribute

                                  session_id: str
                                  

                                  The session ID to resume.

                                  SDKSessionInfo

                                  Bases: BaseModel

                                  Session metadata returned by list_sessions.

                                  Source code in src/clawd_code_sdk/models/session.py
                                  class SDKSessionInfo(BaseModel):
                                      """Session metadata returned by list_sessions."""
                                  
                                      model_config = ConfigDict(extra="forbid")
                                  
                                      session_id: str
                                      """Unique session identifier (UUID)."""
                                  
                                      summary: str
                                      """Display title for the session: custom title, auto-generated summary, or first prompt."""
                                  
                                      last_modified: int
                                      """Last modified time in milliseconds since epoch."""
                                  
                                      file_size: int | None = None
                                      """Session file size in bytes."""
                                  
                                      custom_title: str | None = None
                                      """User-set session title via /rename."""
                                  
                                      first_prompt: str | None = None
                                      """First meaningful user prompt in the session."""
                                  
                                      git_branch: str | None = None
                                      """Git branch at the end of the session."""
                                  
                                      cwd: str | None = None
                                      """Working directory for the session."""
                                  
                                      tag: str | None = None
                                      """User-set session tag."""
                                  
                                      created_at: int | None = None
                                      """Creation time in milliseconds since epoch."""
                                  
                                      archived: bool | None = None
                                      """Whether the session has been archived."""
                                  

                                  archived class-attribute instance-attribute

                                  archived: bool | None = None
                                  

                                  Whether the session has been archived.

                                  created_at class-attribute instance-attribute

                                  created_at: int | None = None
                                  

                                  Creation time in milliseconds since epoch.

                                  custom_title class-attribute instance-attribute

                                  custom_title: str | None = None
                                  

                                  User-set session title via /rename.

                                  cwd class-attribute instance-attribute

                                  cwd: str | None = None
                                  

                                  Working directory for the session.

                                  file_size class-attribute instance-attribute

                                  file_size: int | None = None
                                  

                                  Session file size in bytes.

                                  first_prompt class-attribute instance-attribute

                                  first_prompt: str | None = None
                                  

                                  First meaningful user prompt in the session.

                                  git_branch class-attribute instance-attribute

                                  git_branch: str | None = None
                                  

                                  Git branch at the end of the session.

                                  last_modified instance-attribute

                                  last_modified: int
                                  

                                  Last modified time in milliseconds since epoch.

                                  session_id instance-attribute

                                  session_id: str
                                  

                                  Unique session identifier (UUID).

                                  summary instance-attribute

                                  summary: str
                                  

                                  Display title for the session: custom title, auto-generated summary, or first prompt.

                                  tag class-attribute instance-attribute

                                  tag: str | None = None
                                  

                                  User-set session tag.

                                  Sandbox

                                  Bases: ClaudeCodeBaseModel

                                  Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing.

                                  Source code in src/clawd_code_sdk/models/settings.py
                                  class Sandbox(ClaudeCodeBaseModel):
                                      """Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing."""
                                  
                                      model_config = ConfigDict(
                                          extra="forbid",
                                      )
                                      network: Network | None = None
                                      """
                                      Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.
                                      """
                                      ignore_violations: dict[str, list[str]] | None = Field(None, alias="ignoreViolations")
                                      """
                                      Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands
                                      """
                                      excluded_commands: list[str] | None = Field(None, alias="excludedCommands")
                                      """
                                      Commands that should never run in the sandbox (e.g., ["git", "docker"]). See https://code.claude.com/docs/en/sandboxing#configure-sandboxing
                                      """
                                      auto_allow_bash_if_sandboxed: bool | None = Field(True, alias="autoAllowBashIfSandboxed")
                                      """
                                      Automatically allow bash commands without prompting when they run in the sandbox. Only applies to commands that will run sandboxed. See https://code.claude.com/docs/en/sandboxing#sandbox-modes
                                      """
                                      enable_weaker_network_isolation: bool | None = Field(
                                          False, alias="enableWeakerNetworkIsolation"
                                      )
                                      """
                                      macOS only. Allow access to the system TLS trust service (com.apple.trustd.agent) in the sandbox. Required for Go-based tools like gh, gcloud, and terraform to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Reduces security by opening a potential data exfiltration path. Default: false. See https://code.claude.com/docs/en/sandboxing
                                      """
                                      enable_weaker_nested_sandbox: bool | None = Field(None, alias="enableWeakerNestedSandbox")
                                      """
                                      Enable weaker sandbox mode for unprivileged docker environments where --proc mounting fails. This significantly reduces the strength of the sandbox and should only be used when this risk is acceptable. Default: false (secure). See https://code.claude.com/docs/en/sandboxing#limitations
                                      """
                                      allow_unsandboxed_commands: bool | None = Field(None, alias="allowUnsandboxedCommands")
                                      """
                                      Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true. See https://code.claude.com/docs/en/sandboxing#limitations
                                      """
                                      enabled: bool | None = None
                                      """
                                      Enable sandboxed bash. See https://code.claude.com/docs/en/sandboxing#enable-sandboxing
                                      """
                                      filesystem: Filesystem | None = None
                                      """
                                      Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation
                                      """
                                      ripgrep: Ripgrep | None = None
                                      """
                                      Custom ripgrep configuration for Claude Code's bundled ripgrep support. Overrides the bundled binary and arguments.
                                      """
                                      bwrap_path: str | None = Field(None, alias="bwrapPath", min_length=1)
                                      """
                                      (Managed setting only) Path to custom bubblewrap (bwrap) binary for Linux/WSL sandbox. Overrides default. See https://code.claude.com/docs/en/server-managed-settings
                                      """
                                      socat_path: str | None = Field(None, alias="socatPath", min_length=1)
                                      """
                                      (Managed setting only) Path to custom socat binary for Linux/WSL network proxying. Overrides default. See https://code.claude.com/docs/en/server-managed-settings
                                      """
                                      fail_if_unavailable: bool | None = Field(None, alias="failIfUnavailable")
                                      """
                                      When true, make sandbox startup a hard failure if required sandbox dependencies are missing. Default: false (sandbox is skipped with a warning). See https://code.claude.com/docs/en/sandboxing#enable-sandboxing
                                      """
                                      enabled_platforms: list[Literal["macos", "linux", "wsl", "windows"]] | None = Field(
                                          None, alias="enabledPlatforms"
                                      )
                                      """
                                      Limit the entire sandbox configuration to the listed platforms. On platforms not in the list the sandbox config is inert: no sandbox, no auto-allow, no startup warning, and no failIfUnavailable exit. When omitted, all supported platforms are included. Only honored from managed (policy) settings.
                                      """
                                      credentials: Credentials | None = None
                                      """
                                      Block sandboxed commands from reading credential files and secret environment variables (v2.1.187+). Entries merge across settings scopes. See https://code.claude.com/docs/en/sandboxing#protect-credentials
                                      """
                                      allow_apple_events: bool | None = Field(None, alias="allowAppleEvents")
                                      """
                                      Allow sandboxed commands to send Apple Events on macOS (v2.1.181+). Honored only from user, managed, or CLI settings; project settings cannot enable it. See https://code.claude.com/docs/en/sandboxing#limitations
                                      """
                                  

                                  allow_apple_events class-attribute instance-attribute

                                  allow_apple_events: bool | None = Field(None, alias='allowAppleEvents')
                                  

                                  Allow sandboxed commands to send Apple Events on macOS (v2.1.181+). Honored only from user, managed, or CLI settings; project settings cannot enable it. See https://code.claude.com/docs/en/sandboxing#limitations

                                  allow_unsandboxed_commands class-attribute instance-attribute

                                  allow_unsandboxed_commands: bool | None = Field(None, alias='allowUnsandboxedCommands')
                                  

                                  Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true. See https://code.claude.com/docs/en/sandboxing#limitations

                                  auto_allow_bash_if_sandboxed class-attribute instance-attribute

                                  auto_allow_bash_if_sandboxed: bool | None = Field(True, alias='autoAllowBashIfSandboxed')
                                  

                                  Automatically allow bash commands without prompting when they run in the sandbox. Only applies to commands that will run sandboxed. See https://code.claude.com/docs/en/sandboxing#sandbox-modes

                                  bwrap_path class-attribute instance-attribute

                                  bwrap_path: str | None = Field(None, alias='bwrapPath', min_length=1)
                                  

                                  (Managed setting only) Path to custom bubblewrap (bwrap) binary for Linux/WSL sandbox. Overrides default. See https://code.claude.com/docs/en/server-managed-settings

                                  credentials class-attribute instance-attribute

                                  credentials: Credentials | None = None
                                  

                                  Block sandboxed commands from reading credential files and secret environment variables (v2.1.187+). Entries merge across settings scopes. See https://code.claude.com/docs/en/sandboxing#protect-credentials

                                  enable_weaker_nested_sandbox class-attribute instance-attribute

                                  enable_weaker_nested_sandbox: bool | None = Field(None, alias='enableWeakerNestedSandbox')
                                  

                                  Enable weaker sandbox mode for unprivileged docker environments where --proc mounting fails. This significantly reduces the strength of the sandbox and should only be used when this risk is acceptable. Default: false (secure). See https://code.claude.com/docs/en/sandboxing#limitations

                                  enable_weaker_network_isolation class-attribute instance-attribute

                                  enable_weaker_network_isolation: bool | None = Field(False, alias='enableWeakerNetworkIsolation')
                                  

                                  macOS only. Allow access to the system TLS trust service (com.apple.trustd.agent) in the sandbox. Required for Go-based tools like gh, gcloud, and terraform to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Reduces security by opening a potential data exfiltration path. Default: false. See https://code.claude.com/docs/en/sandboxing

                                  enabled class-attribute instance-attribute

                                  enabled: bool | None = None
                                  

                                  Enable sandboxed bash. See https://code.claude.com/docs/en/sandboxing#enable-sandboxing

                                  enabled_platforms class-attribute instance-attribute

                                  enabled_platforms: list[Literal["macos", "linux", "wsl", "windows"]] | None = Field(
                                      None, alias="enabledPlatforms"
                                  )
                                  

                                  Limit the entire sandbox configuration to the listed platforms. On platforms not in the list the sandbox config is inert: no sandbox, no auto-allow, no startup warning, and no failIfUnavailable exit. When omitted, all supported platforms are included. Only honored from managed (policy) settings.

                                  excluded_commands class-attribute instance-attribute

                                  excluded_commands: list[str] | None = Field(None, alias='excludedCommands')
                                  

                                  Commands that should never run in the sandbox (e.g., ["git", "docker"]). See https://code.claude.com/docs/en/sandboxing#configure-sandboxing

                                  fail_if_unavailable class-attribute instance-attribute

                                  fail_if_unavailable: bool | None = Field(None, alias='failIfUnavailable')
                                  

                                  When true, make sandbox startup a hard failure if required sandbox dependencies are missing. Default: false (sandbox is skipped with a warning). See https://code.claude.com/docs/en/sandboxing#enable-sandboxing

                                  filesystem class-attribute instance-attribute

                                  filesystem: Filesystem | None = None
                                  

                                  Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation

                                  ignore_violations class-attribute instance-attribute

                                  ignore_violations: dict[str, list[str]] | None = Field(None, alias='ignoreViolations')
                                  

                                  Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands

                                  network class-attribute instance-attribute

                                  network: Network | None = None
                                  

                                  Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.

                                  ripgrep class-attribute instance-attribute

                                  ripgrep: Ripgrep | None = None
                                  

                                  Custom ripgrep configuration for Claude Code's bundled ripgrep support. Overrides the bundled binary and arguments.

                                  socat_path class-attribute instance-attribute

                                  socat_path: str | None = Field(None, alias='socatPath', min_length=1)
                                  

                                  (Managed setting only) Path to custom socat binary for Linux/WSL network proxying. Overrides default. See https://code.claude.com/docs/en/server-managed-settings

                                  SdkMcpTool dataclass

                                  Definition for an SDK MCP tool.

                                  Source code in src/clawd_code_sdk/mcp_utils.py
                                  @dataclass
                                  class SdkMcpTool[T]:
                                      """Definition for an SDK MCP tool."""
                                  
                                      name: str
                                      description: str
                                      input_schema: type[T] | dict[str, Any]
                                      handler: Callable[[T], Awaitable[dict[str, Any]]]
                                      title: str | None = None
                                      annotations: ToolAnnotations | None = None
                                      output_schema: dict[str, Any] | None = None
                                      meta: dict[str, Any] | None = None
                                      search_hint: str | None = None
                                      always_load: bool | None = None
                                      max_result_size_chars: int | None = None
                                  

                                  SdkPluginConfig

                                  Bases: ClaudeCodeBaseModel

                                  SDK plugin configuration.

                                  Currently only local plugins are supported via the 'local' type.

                                  Source code in src/clawd_code_sdk/models/mcp.py
                                  class SdkPluginConfig(ClaudeCodeBaseModel):
                                      """SDK plugin configuration.
                                  
                                      Currently only local plugins are supported via the 'local' type.
                                      """
                                  
                                      type: Literal["local"] = "local"
                                      path: str
                                      skip_mcp_discovery: bool | None = None
                                      """Load skills/hooks/agents/commands but not the plugin's MCP servers.
                                  
                                      Use when the SDK host owns this plugin's MCP connections.
                                      """
                                  

                                  skip_mcp_discovery class-attribute instance-attribute

                                  skip_mcp_discovery: bool | None = None
                                  

                                  Load skills/hooks/agents/commands but not the plugin's MCP servers.

                                  Use when the SDK host owns this plugin's MCP connections.

                                  ServerError

                                  Bases: APIError

                                  Raised when the API server encounters an error (500/529).

                                  This includes internal server errors (500) and overload errors (529). Applications should implement retry logic for transient server errors.

                                  Source code in src/clawd_code_sdk/_errors.py
                                  class ServerError(APIError):
                                      """Raised when the API server encounters an error (500/529).
                                  
                                      This includes internal server errors (500) and overload errors (529).
                                      Applications should implement retry logic for transient server errors.
                                      """
                                  
                                      def __init__(self, message: str, model: Model | None = None) -> None:
                                          super().__init__(message, "server_error", model)
                                  

                                  Session

                                  A managed Claude session wrapping a ClaudeSDKClient.

                                  Not constructed directly — use SessionManager.create_session().

                                  Source code in src/clawd_code_sdk/session.py
                                  class Session:
                                      """A managed Claude session wrapping a ClaudeSDKClient.
                                  
                                      Not constructed directly — use ``SessionManager.create_session()``.
                                      """
                                  
                                      def __init__(self, session_id: str, client: ClaudeSDKClient) -> None:
                                          self._session_id = session_id
                                          self._client = client
                                          self._state: SessionState = "created"
                                          self._turns: list[ConversationTurn] = []
                                          self._created_at = datetime.now(UTC)
                                          self._last_activity = self._created_at
                                  
                                      @property
                                      def session_id(self) -> str:
                                          return self._session_id
                                  
                                      @property
                                      def state(self) -> SessionState:
                                          return self._state
                                  
                                      @property
                                      def client(self) -> ClaudeSDKClient:
                                          """Access the underlying client for low-level operations."""
                                          return self._client
                                  
                                      @property
                                      def turns(self) -> list[ConversationTurn]:
                                          """All completed conversation turns in this session."""
                                          return list(self._turns)
                                  
                                      @property
                                      def total_cost_usd(self) -> float:
                                          """Accumulated cost across all turns."""
                                          return sum(t.cost_usd for t in self._turns if t.cost_usd is not None)
                                  
                                      @property
                                      def snapshot(self) -> SessionSnapshot:
                                          """Current metadata snapshot."""
                                          return SessionSnapshot(
                                              session_id=self._session_id,
                                              state=self._state,
                                              model=self._client.options.model,
                                              cwd=str(self._client.options.cwd) if self._client.options.cwd else None,
                                              created_at=self._created_at,
                                              last_activity=self._last_activity,
                                              turn_count=len(self._turns),
                                              total_cost_usd=self.total_cost_usd,
                                          )
                                  
                                      async def send(self, prompt: str) -> AsyncIterator[Message]:
                                          """Send a prompt and stream response messages.
                                  
                                          Combines ``client.query()`` + ``client.receive_response()`` into one call.
                                          Yields every message including the final ``ResultMessage``, then stops.
                                          The completed ``ConversationTurn`` is appended to ``self.turns``.
                                  
                                          Raises:
                                              RuntimeError: If the session is not in IDLE state.
                                          """
                                          if self._state != "idle":
                                              msg = (
                                                  f"Cannot send: session {self._session_id!r} is in state "
                                                  f"{self._state!r}, expected 'idle'"
                                              )
                                              raise RuntimeError(msg)
                                  
                                          self._state = "responding"
                                          self._last_activity = datetime.now(UTC)
                                          collected: list[Message] = []
                                  
                                          completed = False
                                          sent = False
                                          try:
                                              # Shielded (anyio scopes): once the write starts, the prompt is sent, so
                                              # `sent` tells whether a turn may be running.
                                              with anyio.CancelScope(shield=True):
                                                  await self._client.query(prompt)
                                              sent = True
                                              async for message in self._client.receive_response():
                                                  collected.append(message)
                                                  if isinstance(message, ResultMessage):
                                                      # Before the yield: a consumer stopping at the result ends a full turn.
                                                      completed = True
                                                      turn = _extract_turn(collected, message)
                                                      self._turns.append(turn)
                                                      self._last_activity = datetime.now(UTC)
                                                  yield message
                                              self._state = "idle"
                                          except Exception:
                                              self._state = "error"
                                              raise
                                          except BaseException:
                                              # The consumer broke out (GeneratorExit) or was cancelled: stop the turn
                                              # if it is still running, so the next send() starts from a quiet session.
                                              if completed or not sent:
                                                  self._state = "idle"
                                              else:
                                                  self._state = "error"  # unless the turn is wound down below
                                                  with anyio.CancelScope(shield=True):
                                                      try:
                                                          await self._finish_interrupted_turn()
                                                      except Exception:
                                                          logger.warning("Could not stop the interrupted turn", exc_info=True)
                                                      else:
                                                          self._state = "idle"
                                              raise
                                  
                                      async def _finish_interrupted_turn(self) -> None:
                                          """Interrupt the running turn and read it to its end (its result message).
                                  
                                          Otherwise the next ``send()`` would receive the rest of this turn.
                                  
                                          Raises:
                                              TimeoutError: The turn didn't end within ``INTERRUPT_DRAIN_TIMEOUT``.
                                          """
                                          await self._client.interrupt()
                                          with anyio.fail_after(INTERRUPT_DRAIN_TIMEOUT):
                                              async for message in self._client.receive_response():
                                                  if isinstance(message, ResultMessage):
                                                      break
                                  
                                      async def send_and_collect(self, prompt: str) -> ConversationTurn:
                                          """Send a prompt and return the full collected response.
                                  
                                          Convenience for cases where streaming is not needed.
                                  
                                          Raises:
                                              RuntimeError: If the session is not in IDLE state or no
                                                  ResultMessage was received.
                                          """
                                          last_turn_count = len(self._turns)
                                          async for _ in self.send(prompt):
                                              pass
                                          if len(self._turns) <= last_turn_count:
                                              msg = "No ResultMessage received — response may have been interrupted"
                                              raise RuntimeError(msg)
                                          return self._turns[-1]
                                  
                                      async def interrupt(self) -> None:
                                          """Send interrupt signal to the current response."""
                                          await self._client.interrupt()
                                  
                                      async def set_model(self, model: str | None = None) -> None:
                                          """Change the AI model during conversation."""
                                          await self._client.set_model(model)
                                  
                                      async def set_permission_mode(
                                          self, mode: PermissionMode
                                      ) -> SDKControlSetPermissionModeResponse | None:
                                          """Change permission mode during conversation (returns the mode now in effect)."""
                                          return await self._client.set_permission_mode(mode)
                                  
                                      async def set_max_thinking_tokens(self, max_thinking_tokens: int) -> None:
                                          """Set the maximum number of thinking tokens."""
                                          await self._client.set_max_thinking_tokens(max_thinking_tokens)
                                  
                                      async def close(self) -> None:
                                          """Disconnect and release resources. Idempotent."""
                                          if self._state == "disconnected":
                                              return
                                          try:
                                              await self._client.disconnect()
                                          finally:
                                              self._state = "disconnected"
                                  

                                  client property

                                  Access the underlying client for low-level operations.

                                  snapshot property

                                  snapshot: SessionSnapshot
                                  

                                  Current metadata snapshot.

                                  total_cost_usd property

                                  total_cost_usd: float
                                  

                                  Accumulated cost across all turns.

                                  turns property

                                  turns: list[ConversationTurn]
                                  

                                  All completed conversation turns in this session.

                                  close async

                                  close() -> None
                                  

                                  Disconnect and release resources. Idempotent.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def close(self) -> None:
                                      """Disconnect and release resources. Idempotent."""
                                      if self._state == "disconnected":
                                          return
                                      try:
                                          await self._client.disconnect()
                                      finally:
                                          self._state = "disconnected"
                                  

                                  interrupt async

                                  interrupt() -> None
                                  

                                  Send interrupt signal to the current response.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def interrupt(self) -> None:
                                      """Send interrupt signal to the current response."""
                                      await self._client.interrupt()
                                  

                                  send async

                                  send(prompt: str) -> AsyncIterator[Message]
                                  

                                  Send a prompt and stream response messages.

                                  Combines client.query() + client.receive_response() into one call. Yields every message including the final ResultMessage, then stops. The completed ConversationTurn is appended to self.turns.

                                  Raises:

                                  Type Description
                                  RuntimeError

                                  If the session is not in IDLE state.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def send(self, prompt: str) -> AsyncIterator[Message]:
                                      """Send a prompt and stream response messages.
                                  
                                      Combines ``client.query()`` + ``client.receive_response()`` into one call.
                                      Yields every message including the final ``ResultMessage``, then stops.
                                      The completed ``ConversationTurn`` is appended to ``self.turns``.
                                  
                                      Raises:
                                          RuntimeError: If the session is not in IDLE state.
                                      """
                                      if self._state != "idle":
                                          msg = (
                                              f"Cannot send: session {self._session_id!r} is in state "
                                              f"{self._state!r}, expected 'idle'"
                                          )
                                          raise RuntimeError(msg)
                                  
                                      self._state = "responding"
                                      self._last_activity = datetime.now(UTC)
                                      collected: list[Message] = []
                                  
                                      completed = False
                                      sent = False
                                      try:
                                          # Shielded (anyio scopes): once the write starts, the prompt is sent, so
                                          # `sent` tells whether a turn may be running.
                                          with anyio.CancelScope(shield=True):
                                              await self._client.query(prompt)
                                          sent = True
                                          async for message in self._client.receive_response():
                                              collected.append(message)
                                              if isinstance(message, ResultMessage):
                                                  # Before the yield: a consumer stopping at the result ends a full turn.
                                                  completed = True
                                                  turn = _extract_turn(collected, message)
                                                  self._turns.append(turn)
                                                  self._last_activity = datetime.now(UTC)
                                              yield message
                                          self._state = "idle"
                                      except Exception:
                                          self._state = "error"
                                          raise
                                      except BaseException:
                                          # The consumer broke out (GeneratorExit) or was cancelled: stop the turn
                                          # if it is still running, so the next send() starts from a quiet session.
                                          if completed or not sent:
                                              self._state = "idle"
                                          else:
                                              self._state = "error"  # unless the turn is wound down below
                                              with anyio.CancelScope(shield=True):
                                                  try:
                                                      await self._finish_interrupted_turn()
                                                  except Exception:
                                                      logger.warning("Could not stop the interrupted turn", exc_info=True)
                                                  else:
                                                      self._state = "idle"
                                          raise
                                  

                                  send_and_collect async

                                  send_and_collect(prompt: str) -> ConversationTurn
                                  

                                  Send a prompt and return the full collected response.

                                  Convenience for cases where streaming is not needed.

                                  Raises:

                                  Type Description
                                  RuntimeError

                                  If the session is not in IDLE state or no ResultMessage was received.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def send_and_collect(self, prompt: str) -> ConversationTurn:
                                      """Send a prompt and return the full collected response.
                                  
                                      Convenience for cases where streaming is not needed.
                                  
                                      Raises:
                                          RuntimeError: If the session is not in IDLE state or no
                                              ResultMessage was received.
                                      """
                                      last_turn_count = len(self._turns)
                                      async for _ in self.send(prompt):
                                          pass
                                      if len(self._turns) <= last_turn_count:
                                          msg = "No ResultMessage received — response may have been interrupted"
                                          raise RuntimeError(msg)
                                      return self._turns[-1]
                                  

                                  set_max_thinking_tokens async

                                  set_max_thinking_tokens(max_thinking_tokens: int) -> None
                                  

                                  Set the maximum number of thinking tokens.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def set_max_thinking_tokens(self, max_thinking_tokens: int) -> None:
                                      """Set the maximum number of thinking tokens."""
                                      await self._client.set_max_thinking_tokens(max_thinking_tokens)
                                  

                                  set_model async

                                  set_model(model: str | None = None) -> None
                                  

                                  Change the AI model during conversation.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def set_model(self, model: str | None = None) -> None:
                                      """Change the AI model during conversation."""
                                      await self._client.set_model(model)
                                  

                                  set_permission_mode async

                                  set_permission_mode(mode: PermissionMode) -> SDKControlSetPermissionModeResponse | None
                                  

                                  Change permission mode during conversation (returns the mode now in effect).

                                  Source code in src/clawd_code_sdk/session.py
                                  async def set_permission_mode(
                                      self, mode: PermissionMode
                                  ) -> SDKControlSetPermissionModeResponse | None:
                                      """Change permission mode during conversation (returns the mode now in effect)."""
                                      return await self._client.set_permission_mode(mode)
                                  

                                  SessionManager

                                  Manages multiple concurrent Claude SDK sessions.

                                  Usage::

                                  async with SessionManager() as manager:
                                      s1 = await manager.create_session("coding", options=opts)
                                      turn = await s1.send_and_collect("Explain this codebase")
                                      print(turn.text)
                                  
                                      s2 = await manager.create_session("review", options=opts, prompt="Review my PR")
                                      async for msg in s2.send("What issues did you find?"):
                                          ...
                                  
                                  Source code in src/clawd_code_sdk/session.py
                                  class SessionManager:
                                      """Manages multiple concurrent Claude SDK sessions.
                                  
                                      Usage::
                                  
                                          async with SessionManager() as manager:
                                              s1 = await manager.create_session("coding", options=opts)
                                              turn = await s1.send_and_collect("Explain this codebase")
                                              print(turn.text)
                                  
                                              s2 = await manager.create_session("review", options=opts, prompt="Review my PR")
                                              async for msg in s2.send("What issues did you find?"):
                                                  ...
                                      """
                                  
                                      def __init__(self, *, max_concurrent_sessions: int | None = None) -> None:
                                          """Initialize the session manager.
                                  
                                          Args:
                                              max_concurrent_sessions: Optional cap on simultaneous connected
                                                  sessions. ``create_session`` raises if exceeded.
                                          """
                                          self._sessions: dict[str, Session] = {}
                                          self._max_concurrent_sessions = max_concurrent_sessions
                                  
                                      # ── Session lifecycle ────────────────────────────────────────
                                  
                                      async def create_session(
                                          self,
                                          session_id: str | None = None,
                                          *,
                                          options: ClaudeAgentOptions | None = None,
                                          transport: Transport | None = None,
                                          prompt: str | None = None,
                                          connect: bool = True,
                                      ) -> Session:
                                          """Create and optionally connect a new session.
                                  
                                          Args:
                                              session_id: Explicit ID, or auto-generated UUID if None.
                                              options: Session-specific options.
                                              transport: Optional custom transport.
                                              prompt: If provided, sent as the initial prompt on connect.
                                              connect: If True (default), connect immediately.
                                  
                                          Raises:
                                              ValueError: If session_id already exists.
                                              RuntimeError: If max_concurrent_sessions would be exceeded.
                                          """
                                          sid = session_id or uuid.uuid4().hex
                                          if sid in self._sessions:
                                              msg = f"Session {sid!r} already exists"
                                              raise ValueError(msg)
                                  
                                          if self._max_concurrent_sessions is not None:
                                              active_count = sum(
                                                  1
                                                  for s in self._sessions.values()
                                                  if s.state in ("idle", "responding", "connecting")
                                              )
                                              if active_count >= self._max_concurrent_sessions:
                                                  msg = f"Maximum concurrent sessions ({self._max_concurrent_sessions}) reached"
                                                  raise RuntimeError(msg)
                                  
                                          client = ClaudeSDKClient(options=options, transport=transport)
                                          session = Session(sid, client)
                                          self._sessions[sid] = session
                                  
                                          if connect:
                                              session._state = "connecting"
                                              try:
                                                  await client.connect()
                                                  if prompt:
                                                      await client.query(prompt)
                                                  session._state = "idle"
                                                  session._last_activity = datetime.now(UTC)
                                              except Exception:
                                                  session._state = "error"
                                                  raise
                                  
                                          return session
                                  
                                      async def resume_session(
                                          self,
                                          session_id: str,
                                          *,
                                          options: ClaudeAgentOptions | None = None,
                                          transport: Transport | None = None,
                                      ) -> Session:
                                          """Resume a previously persisted session by ID.
                                  
                                          Sets ``session`` to a :class:`ResumeSession` config on the options,
                                          then connects.
                                  
                                          Args:
                                              session_id: The session ID to resume.
                                              options: Session-specific options (``session`` is set automatically).
                                              transport: Optional custom transport.
                                  
                                          Raises:
                                              ValueError: If session_id already exists in this manager.
                                          """
                                          from clawd_code_sdk.models.options import ResumeSession
                                  
                                          base = options or Opts()
                                          merged = replace(base, session=ResumeSession(session_id=session_id))
                                          return await self.create_session(
                                              session_id=session_id,
                                              options=merged,
                                              transport=transport,
                                          )
                                  
                                      # ── Session access ───────────────────────────────────────────
                                  
                                      def get_session(self, session_id: str) -> Session:
                                          """Get a session by ID.
                                  
                                          Raises:
                                              KeyError: If session_id not found.
                                          """
                                          try:
                                              return self._sessions[session_id]
                                          except KeyError:
                                              msg = f"Session {session_id!r} not found"
                                              raise KeyError(msg) from None
                                  
                                      def __getitem__(self, session_id: str) -> Session:
                                          """Alias for ``get_session()``."""
                                          return self.get_session(session_id)
                                  
                                      def __contains__(self, session_id: str) -> bool:
                                          return session_id in self._sessions
                                  
                                      def __len__(self) -> int:
                                          return len(self._sessions)
                                  
                                      def __iter__(self) -> Iterator[str]:
                                          """Iterate over session IDs."""
                                          return iter(self._sessions)
                                  
                                      @property
                                      def sessions(self) -> dict[str, Session]:
                                          """All sessions (any state). Returns a copy."""
                                          return dict(self._sessions)
                                  
                                      @property
                                      def active_sessions(self) -> dict[str, Session]:
                                          """Sessions in IDLE or RESPONDING state."""
                                          return {sid: s for sid, s in self._sessions.items() if s.state in ("idle", "responding")}
                                  
                                      # ── Cleanup ──────────────────────────────────────────────────
                                  
                                      async def close_session(self, session_id: str) -> None:
                                          """Close and remove a specific session.
                                  
                                          Raises:
                                              KeyError: If session_id not found.
                                          """
                                          session = self.get_session(session_id)
                                          await session.close()
                                          del self._sessions[session_id]
                                  
                                      async def close_all(self) -> None:
                                          """Close all sessions, concurrently. Errors during individual closes are suppressed."""
                                          sessions = list(self._sessions.values())
                                          await asyncio.gather(*(s.close() for s in sessions), return_exceptions=True)
                                          self._sessions.clear()
                                  
                                      # ── Aggregate stats ──────────────────────────────────────────
                                  
                                      @property
                                      def total_cost_usd(self) -> float:
                                          """Sum of costs across all sessions."""
                                          return sum(s.total_cost_usd for s in self._sessions.values())
                                  
                                      def snapshots(self) -> dict[str, SessionSnapshot]:
                                          """Snapshots of all sessions."""
                                          return {sid: s.snapshot for sid, s in self._sessions.items()}
                                  
                                      # ── Context manager ──────────────────────────────────────────
                                  
                                      async def __aenter__(self) -> Self:
                                          return self
                                  
                                      async def __aexit__(self, *args: object) -> None:
                                          await self.close_all()
                                  

                                  active_sessions property

                                  active_sessions: dict[str, Session]
                                  

                                  Sessions in IDLE or RESPONDING state.

                                  sessions property

                                  sessions: dict[str, Session]
                                  

                                  All sessions (any state). Returns a copy.

                                  total_cost_usd property

                                  total_cost_usd: float
                                  

                                  Sum of costs across all sessions.

                                  __getitem__

                                  __getitem__(session_id: str) -> Session
                                  

                                  Alias for get_session().

                                  Source code in src/clawd_code_sdk/session.py
                                  def __getitem__(self, session_id: str) -> Session:
                                      """Alias for ``get_session()``."""
                                      return self.get_session(session_id)
                                  

                                  __init__

                                  __init__(*, max_concurrent_sessions: int | None = None) -> None
                                  

                                  Initialize the session manager.

                                  Parameters:

                                  Name Type Description Default
                                  max_concurrent_sessions int | None

                                  Optional cap on simultaneous connected sessions. create_session raises if exceeded.

                                  None
                                  Source code in src/clawd_code_sdk/session.py
                                  def __init__(self, *, max_concurrent_sessions: int | None = None) -> None:
                                      """Initialize the session manager.
                                  
                                      Args:
                                          max_concurrent_sessions: Optional cap on simultaneous connected
                                              sessions. ``create_session`` raises if exceeded.
                                      """
                                      self._sessions: dict[str, Session] = {}
                                      self._max_concurrent_sessions = max_concurrent_sessions
                                  

                                  __iter__

                                  __iter__() -> Iterator[str]
                                  

                                  Iterate over session IDs.

                                  Source code in src/clawd_code_sdk/session.py
                                  def __iter__(self) -> Iterator[str]:
                                      """Iterate over session IDs."""
                                      return iter(self._sessions)
                                  

                                  close_all async

                                  close_all() -> None
                                  

                                  Close all sessions, concurrently. Errors during individual closes are suppressed.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def close_all(self) -> None:
                                      """Close all sessions, concurrently. Errors during individual closes are suppressed."""
                                      sessions = list(self._sessions.values())
                                      await asyncio.gather(*(s.close() for s in sessions), return_exceptions=True)
                                      self._sessions.clear()
                                  

                                  close_session async

                                  close_session(session_id: str) -> None
                                  

                                  Close and remove a specific session.

                                  Raises:

                                  Type Description
                                  KeyError

                                  If session_id not found.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def close_session(self, session_id: str) -> None:
                                      """Close and remove a specific session.
                                  
                                      Raises:
                                          KeyError: If session_id not found.
                                      """
                                      session = self.get_session(session_id)
                                      await session.close()
                                      del self._sessions[session_id]
                                  

                                  create_session async

                                  create_session(
                                      session_id: str | None = None,
                                      *,
                                      options: ClaudeAgentOptions | None = None,
                                      transport: Transport | None = None,
                                      prompt: str | None = None,
                                      connect: bool = True,
                                  ) -> Session
                                  

                                  Create and optionally connect a new session.

                                  Parameters:

                                  Name Type Description Default
                                  session_id str | None

                                  Explicit ID, or auto-generated UUID if None.

                                  None
                                  options ClaudeAgentOptions | None

                                  Session-specific options.

                                  None
                                  transport Transport | None

                                  Optional custom transport.

                                  None
                                  prompt str | None

                                  If provided, sent as the initial prompt on connect.

                                  None
                                  connect bool

                                  If True (default), connect immediately.

                                  True

                                  Raises:

                                  Type Description
                                  ValueError

                                  If session_id already exists.

                                  RuntimeError

                                  If max_concurrent_sessions would be exceeded.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def create_session(
                                      self,
                                      session_id: str | None = None,
                                      *,
                                      options: ClaudeAgentOptions | None = None,
                                      transport: Transport | None = None,
                                      prompt: str | None = None,
                                      connect: bool = True,
                                  ) -> Session:
                                      """Create and optionally connect a new session.
                                  
                                      Args:
                                          session_id: Explicit ID, or auto-generated UUID if None.
                                          options: Session-specific options.
                                          transport: Optional custom transport.
                                          prompt: If provided, sent as the initial prompt on connect.
                                          connect: If True (default), connect immediately.
                                  
                                      Raises:
                                          ValueError: If session_id already exists.
                                          RuntimeError: If max_concurrent_sessions would be exceeded.
                                      """
                                      sid = session_id or uuid.uuid4().hex
                                      if sid in self._sessions:
                                          msg = f"Session {sid!r} already exists"
                                          raise ValueError(msg)
                                  
                                      if self._max_concurrent_sessions is not None:
                                          active_count = sum(
                                              1
                                              for s in self._sessions.values()
                                              if s.state in ("idle", "responding", "connecting")
                                          )
                                          if active_count >= self._max_concurrent_sessions:
                                              msg = f"Maximum concurrent sessions ({self._max_concurrent_sessions}) reached"
                                              raise RuntimeError(msg)
                                  
                                      client = ClaudeSDKClient(options=options, transport=transport)
                                      session = Session(sid, client)
                                      self._sessions[sid] = session
                                  
                                      if connect:
                                          session._state = "connecting"
                                          try:
                                              await client.connect()
                                              if prompt:
                                                  await client.query(prompt)
                                              session._state = "idle"
                                              session._last_activity = datetime.now(UTC)
                                          except Exception:
                                              session._state = "error"
                                              raise
                                  
                                      return session
                                  

                                  get_session

                                  get_session(session_id: str) -> Session
                                  

                                  Get a session by ID.

                                  Raises:

                                  Type Description
                                  KeyError

                                  If session_id not found.

                                  Source code in src/clawd_code_sdk/session.py
                                  def get_session(self, session_id: str) -> Session:
                                      """Get a session by ID.
                                  
                                      Raises:
                                          KeyError: If session_id not found.
                                      """
                                      try:
                                          return self._sessions[session_id]
                                      except KeyError:
                                          msg = f"Session {session_id!r} not found"
                                          raise KeyError(msg) from None
                                  

                                  resume_session async

                                  resume_session(
                                      session_id: str,
                                      *,
                                      options: ClaudeAgentOptions | None = None,
                                      transport: Transport | None = None,
                                  ) -> Session
                                  

                                  Resume a previously persisted session by ID.

                                  Sets session to a :class:ResumeSession config on the options, then connects.

                                  Parameters:

                                  Name Type Description Default
                                  session_id str

                                  The session ID to resume.

                                  required
                                  options ClaudeAgentOptions | None

                                  Session-specific options (session is set automatically).

                                  None
                                  transport Transport | None

                                  Optional custom transport.

                                  None

                                  Raises:

                                  Type Description
                                  ValueError

                                  If session_id already exists in this manager.

                                  Source code in src/clawd_code_sdk/session.py
                                  async def resume_session(
                                      self,
                                      session_id: str,
                                      *,
                                      options: ClaudeAgentOptions | None = None,
                                      transport: Transport | None = None,
                                  ) -> Session:
                                      """Resume a previously persisted session by ID.
                                  
                                      Sets ``session`` to a :class:`ResumeSession` config on the options,
                                      then connects.
                                  
                                      Args:
                                          session_id: The session ID to resume.
                                          options: Session-specific options (``session`` is set automatically).
                                          transport: Optional custom transport.
                                  
                                      Raises:
                                          ValueError: If session_id already exists in this manager.
                                      """
                                      from clawd_code_sdk.models.options import ResumeSession
                                  
                                      base = options or Opts()
                                      merged = replace(base, session=ResumeSession(session_id=session_id))
                                      return await self.create_session(
                                          session_id=session_id,
                                          options=merged,
                                          transport=transport,
                                      )
                                  

                                  snapshots

                                  snapshots() -> dict[str, SessionSnapshot]
                                  

                                  Snapshots of all sessions.

                                  Source code in src/clawd_code_sdk/session.py
                                  def snapshots(self) -> dict[str, SessionSnapshot]:
                                      """Snapshots of all sessions."""
                                      return {sid: s.snapshot for sid, s in self._sessions.items()}
                                  

                                  SessionMessage

                                  Bases: BaseModel

                                  A message from a session transcript.

                                  Returned by get_session_messages for reading historical session data.

                                  Source code in src/clawd_code_sdk/models/session.py
                                  class SessionMessage(BaseModel):
                                      """A message from a session transcript.
                                  
                                      Returned by ``get_session_messages`` for reading historical session data.
                                      """
                                  
                                      type: Literal["user", "assistant", "system"]
                                      uuid: str
                                      session_id: str
                                      message: Any
                                      # timestamp: str
                                      parent_tool_use_id: str | None = None
                                      """For subagent messages: id of the Agent ``tool_use`` in the parent session that spawned
                                      the subagent (from its ``.meta.json`` sidecar). ``None`` for top-level session messages."""
                                      parent_agent_id: str | None = None
                                      """For messages of nested subagents: agent id of the subagent that spawned this one."""
                                  

                                  parent_agent_id class-attribute instance-attribute

                                  parent_agent_id: str | None = None
                                  

                                  For messages of nested subagents: agent id of the subagent that spawned this one.

                                  parent_tool_use_id class-attribute instance-attribute

                                  parent_tool_use_id: str | None = None
                                  

                                  For subagent messages: id of the Agent tool_use in the parent session that spawned the subagent (from its .meta.json sidecar). None for top-level session messages.

                                  SessionSnapshot dataclass

                                  Read-only snapshot of session metadata at a point in time.

                                  Source code in src/clawd_code_sdk/session.py
                                  @dataclass(frozen=True)
                                  class SessionSnapshot:
                                      """Read-only snapshot of session metadata at a point in time."""
                                  
                                      session_id: str
                                      state: SessionState
                                      model: str | None
                                      cwd: str | None
                                      created_at: datetime
                                      last_activity: datetime
                                      turn_count: int
                                      total_cost_usd: float
                                  

                                  SettingsSource

                                  Bases: BaseModel

                                  A single settings source with its raw settings.

                                  Source code in src/clawd_code_sdk/models/control.py
                                  class SettingsSource(BaseModel):
                                      """A single settings source with its raw settings."""
                                  
                                      source: str
                                      """The source name (e.g. 'user', 'project', 'flagSettings')."""
                                  
                                      settings: dict[str, Any]
                                      """The raw settings from this source."""
                                  

                                  settings instance-attribute

                                  settings: dict[str, Any]
                                  

                                  The raw settings from this source.

                                  source instance-attribute

                                  source: str
                                  

                                  The source name (e.g. 'user', 'project', 'flagSettings').

                                  StopHookInput

                                  Bases: BaseHookInput

                                  Input data for Stop hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class StopHookInput(BaseHookInput):
                                      """Input data for Stop hook events."""
                                  
                                      hook_event_name: Literal["Stop"]
                                      stop_hook_active: bool
                                  

                                  SubagentStartHookInput

                                  Bases: BaseHookInput

                                  Input data for SubagentStart hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class SubagentStartHookInput(BaseHookInput):
                                      """Input data for SubagentStart hook events."""
                                  
                                      hook_event_name: Literal["SubagentStart"]
                                      agent_id: str
                                      agent_type: str
                                  

                                  SubagentStartHookSpecificOutput

                                  Bases: TypedDict

                                  Hook-specific output for SubagentStart events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class SubagentStartHookSpecificOutput(TypedDict):
                                      """Hook-specific output for SubagentStart events."""
                                  
                                      hookEventName: Literal["SubagentStart"]
                                      additionalContext: NotRequired[str]
                                  

                                  SubagentStopHookInput

                                  Bases: BaseHookInput

                                  Input data for SubagentStop hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class SubagentStopHookInput(BaseHookInput):
                                      """Input data for SubagentStop hook events."""
                                  
                                      hook_event_name: Literal["SubagentStop"]
                                      stop_hook_active: bool
                                      agent_id: str
                                      agent_transcript_path: str
                                      agent_type: str
                                  

                                  TextBlock

                                  Bases: BaseContentBlock

                                  Text content block.

                                  Source code in src/clawd_code_sdk/models/content_blocks.py
                                  class TextBlock(BaseContentBlock):
                                      """Text content block."""
                                  
                                      type: Literal["text"] = "text"
                                      text: str
                                  
                                      def to_otel(self) -> TextPart:
                                          from logfire._internal.integrations.llm_providers.semconv import TextPart
                                  
                                          return TextPart(type="text", content=self.text)
                                  

                                  ThinkingBlock

                                  Bases: BaseContentBlock

                                  Thinking/reasoning content block.

                                  Source code in src/clawd_code_sdk/models/content_blocks.py
                                  class ThinkingBlock(BaseContentBlock):
                                      """Thinking/reasoning content block."""
                                  
                                      type: Literal["thinking"] = "thinking"
                                      thinking: str
                                      signature: str = ""
                                  
                                      def to_otel(self) -> ReasoningPart:
                                          from logfire._internal.integrations.llm_providers.semconv import ReasoningPart
                                  
                                          return ReasoningPart(type="reasoning", content=self.thinking)
                                  

                                  ThinkingConfigAdaptive

                                  Bases: ClaudeCodeBaseModel

                                  Adaptive thinking configuration - model decides thinking budget.

                                  Source code in src/clawd_code_sdk/models/thinking.py
                                  class ThinkingConfigAdaptive(ClaudeCodeBaseModel):
                                      """Adaptive thinking configuration - model decides thinking budget."""
                                  
                                      type: Literal["adaptive"] = "adaptive"
                                  
                                      display: ThinkingDisplay | None = None
                                      """Controls how thinking content appears in the response.
                                      When set to `summarized`, thinking is returned normally. When set to `omitted`,
                                      thinking content is redacted but a signature is returned for multi-turn
                                      continuity. Defaults to `summarized`.
                                      """
                                  

                                  display class-attribute instance-attribute

                                  display: ThinkingDisplay | None = None
                                  

                                  Controls how thinking content appears in the response. When set to summarized, thinking is returned normally. When set to omitted, thinking content is redacted but a signature is returned for multi-turn continuity. Defaults to summarized.

                                  ThinkingConfigDisabled

                                  Bases: ClaudeCodeBaseModel

                                  Disabled thinking configuration.

                                  Source code in src/clawd_code_sdk/models/thinking.py
                                  class ThinkingConfigDisabled(ClaudeCodeBaseModel):
                                      """Disabled thinking configuration."""
                                  
                                      type: Literal["disabled"] = "disabled"
                                  

                                  ThinkingConfigEnabled

                                  Bases: ClaudeCodeBaseModel

                                  Enabled thinking configuration with explicit token budget.

                                  Source code in src/clawd_code_sdk/models/thinking.py
                                  class ThinkingConfigEnabled(ClaudeCodeBaseModel):
                                      """Enabled thinking configuration with explicit token budget."""
                                  
                                      type: Literal["enabled"] = "enabled"
                                  
                                      budget_tokens: int
                                      """Determines how many tokens Claude can use for its internal reasoning process.
                                      Larger budgets can enable more thorough analysis for complex problems, improving
                                      response quality.
                                      Must be ≥1024 and less than `max_tokens`.
                                      See
                                      [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)
                                      for details.
                                      """
                                  
                                      display: ThinkingDisplay | None = None
                                      """Controls how thinking content appears in the response.
                                      When set to `summarized`, thinking is returned normally. When set to `omitted`,
                                      thinking content is redacted but a signature is returned for multi-turn
                                      continuity. Defaults to `summarized`.
                                      """
                                  

                                  budget_tokens instance-attribute

                                  budget_tokens: int
                                  

                                  Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality. Must be ≥1024 and less than max_tokens. See extended thinking for details.

                                  display class-attribute instance-attribute

                                  display: ThinkingDisplay | None = None
                                  

                                  Controls how thinking content appears in the response. When set to summarized, thinking is returned normally. When set to omitted, thinking content is redacted but a signature is returned for multi-turn continuity. Defaults to summarized.

                                  ToolCallSummary dataclass

                                  Summary of a single tool invocation within a conversation turn.

                                  Source code in src/clawd_code_sdk/session.py
                                  @dataclass(frozen=True)
                                  class ToolCallSummary:
                                      """Summary of a single tool invocation within a conversation turn."""
                                  
                                      tool_use_id: str
                                      tool_name: str
                                      input: ToolInput | dict[str, Any]
                                  

                                  ToolPermissionContext dataclass

                                  Context information for tool permission callbacks.

                                  Source code in src/clawd_code_sdk/models/permissions.py
                                  @dataclass
                                  class ToolPermissionContext:
                                      """Context information for tool permission callbacks."""
                                  
                                      tool_use_id: str
                                      """Unique identifier for this specific tool call within the assistant message.
                                  
                                      Multiple tool calls in the same assistant message will have different tool_use_ids.
                                      """
                                  
                                      # signal: Any | None = None
                                      # """Reserved for future abort signal support. Currently always None."""
                                  
                                      agent_id: str | None = None
                                      """The agent that initiated the tool call, if in a multi-agent setup."""
                                  
                                      decision_reason: str | None = None
                                      """Why the CLI triggered the permission check."""
                                  
                                      suggestions: list[PermissionUpdate] = field(default_factory=list)
                                      """Permission suggestions from CLI for updating permissions.
                                  
                                      So the user won't be prompted again for this tool during this session.
                                      """
                                  
                                      blocked_path: str | None = None
                                      """The file path that triggered the permission request, if applicable.
                                  
                                      For example, when a Bash command tries to access a path outside allowed directories.
                                      """
                                  
                                      title: str | None = None
                                      """Full permission prompt sentence rendered by the bridge.
                                  
                                      E.g. "Claude wants to read foo.txt". Use this as the primary prompt
                                      text when present instead of reconstructing from toolName+input.
                                      """
                                  
                                      display_name: str | None = None
                                      """Short noun phrase for the tool action (e.g. "Read file").
                                  
                                      Suitable for button labels or compact UI.
                                      """
                                  
                                      description: str | None = None
                                      """Human-readable subtitle from the bridge.
                                  
                                      E.g. "Claude will have read and write access to files in ~/Downloads".
                                      """
                                  
                                      tool_name: str | None = None
                                      """The name of the tool that generated this permission request."""
                                  
                                      input: dict[str, Any] | None = None
                                      """The input to the tool that generated this permission request."""
                                  
                                      @classmethod
                                      def from_permission_request(cls, req: SDKControlPermissionRequest) -> Self:
                                          """Create a PermissionContext from a permission request."""
                                          return cls(
                                              tool_use_id=req.tool_use_id,
                                              agent_id=req.agent_id,
                                              decision_reason=req.decision_reason,
                                              suggestions=req.permission_suggestions or [],
                                              blocked_path=req.blocked_path,
                                              title=req.title,
                                              display_name=req.display_name,
                                              description=req.description,
                                              tool_name=req.tool_name,
                                              input=req.input,
                                          )
                                  

                                  agent_id class-attribute instance-attribute

                                  agent_id: str | None = None
                                  

                                  The agent that initiated the tool call, if in a multi-agent setup.

                                  blocked_path class-attribute instance-attribute

                                  blocked_path: str | None = None
                                  

                                  The file path that triggered the permission request, if applicable.

                                  For example, when a Bash command tries to access a path outside allowed directories.

                                  decision_reason class-attribute instance-attribute

                                  decision_reason: str | None = None
                                  

                                  Why the CLI triggered the permission check.

                                  description class-attribute instance-attribute

                                  description: str | None = None
                                  

                                  Human-readable subtitle from the bridge.

                                  E.g. "Claude will have read and write access to files in ~/Downloads".

                                  display_name class-attribute instance-attribute

                                  display_name: str | None = None
                                  

                                  Short noun phrase for the tool action (e.g. "Read file").

                                  Suitable for button labels or compact UI.

                                  input class-attribute instance-attribute

                                  input: dict[str, Any] | None = None
                                  

                                  The input to the tool that generated this permission request.

                                  suggestions class-attribute instance-attribute

                                  suggestions: list[PermissionUpdate] = field(default_factory=list)
                                  

                                  Permission suggestions from CLI for updating permissions.

                                  So the user won't be prompted again for this tool during this session.

                                  title class-attribute instance-attribute

                                  title: str | None = None
                                  

                                  Full permission prompt sentence rendered by the bridge.

                                  E.g. "Claude wants to read foo.txt". Use this as the primary prompt text when present instead of reconstructing from toolName+input.

                                  tool_name class-attribute instance-attribute

                                  tool_name: str | None = None
                                  

                                  The name of the tool that generated this permission request.

                                  tool_use_id instance-attribute

                                  tool_use_id: str
                                  

                                  Unique identifier for this specific tool call within the assistant message.

                                  Multiple tool calls in the same assistant message will have different tool_use_ids.

                                  from_permission_request classmethod

                                  from_permission_request(req: SDKControlPermissionRequest) -> Self
                                  

                                  Create a PermissionContext from a permission request.

                                  Source code in src/clawd_code_sdk/models/permissions.py
                                  @classmethod
                                  def from_permission_request(cls, req: SDKControlPermissionRequest) -> Self:
                                      """Create a PermissionContext from a permission request."""
                                      return cls(
                                          tool_use_id=req.tool_use_id,
                                          agent_id=req.agent_id,
                                          decision_reason=req.decision_reason,
                                          suggestions=req.permission_suggestions or [],
                                          blocked_path=req.blocked_path,
                                          title=req.title,
                                          display_name=req.display_name,
                                          description=req.description,
                                          tool_name=req.tool_name,
                                          input=req.input,
                                      )
                                  

                                  ToolResultBlock

                                  Bases: BaseContentBlock

                                  Tool result content block.

                                  Source code in src/clawd_code_sdk/models/content_blocks.py
                                  class ToolResultBlock(BaseContentBlock):
                                      """Tool result content block."""
                                  
                                      type: Literal["tool_result"] = "tool_result"
                                      tool_use_id: str = ""
                                      content: str | list[dict[str, Any]] | None = None  # BetaContentBlock
                                      is_error: bool | None = None
                                  
                                      def get_parsed_content(self) -> list[ToolResultContentBlock] | str | None:
                                          # TODO: or is it anthropic.types.beta.beta_tool_result_block_param.Content?
                                          from clawd_code_sdk.models.anthropic_types import validate_tool_result_content
                                  
                                          if self.content is None or isinstance(self.content, str):
                                              return self.content
                                          # Validate list content against Anthropic SDK types
                                          return validate_tool_result_content(self.content)
                                  
                                      def extract_text(self) -> str:
                                          """Extract text content from this tool result."""
                                          match self.content:
                                              case None:
                                                  return ""
                                              case str():
                                                  return self.content
                                              case list():
                                                  text_parts = [tc.get("text", "") for tc in self.content if tc.get("type") == "text"]
                                                  return "\n".join(text_parts)
                                              case _ as unreachable:
                                                  assert_never(unreachable)
                                  
                                      def to_otel(self) -> ToolCallResponsePart:
                                          from logfire._internal.integrations.llm_providers.semconv import ToolCallResponsePart
                                  
                                          res = {"content": self.content} if isinstance(self.content, list) else self.content
                                          return ToolCallResponsePart(
                                              type="tool_call_response", id=self.tool_use_id or "", response=res
                                          )
                                  

                                  extract_text

                                  extract_text() -> str
                                  

                                  Extract text content from this tool result.

                                  Source code in src/clawd_code_sdk/models/content_blocks.py
                                  def extract_text(self) -> str:
                                      """Extract text content from this tool result."""
                                      match self.content:
                                          case None:
                                              return ""
                                          case str():
                                              return self.content
                                          case list():
                                              text_parts = [tc.get("text", "") for tc in self.content if tc.get("type") == "text"]
                                              return "\n".join(text_parts)
                                          case _ as unreachable:
                                              assert_never(unreachable)
                                  

                                  ToolUseBlock

                                  Bases: BaseContentBlock

                                  Tool use content block.

                                  Source code in src/clawd_code_sdk/models/content_blocks.py
                                  class ToolUseBlock(BaseContentBlock):
                                      """Tool use content block."""
                                  
                                      type: Literal["tool_use"] = "tool_use"
                                      id: str = ""
                                      name: ToolName | str = ""
                                      input: ToolInput | dict[str, Any] = {}
                                      caller: Caller | None = None
                                  
                                      def to_otel(self) -> ToolCallPart:
                                          from logfire._internal.integrations.llm_providers.semconv import ToolCallPart
                                  
                                          args = cast(dict[str, Any], self.input)
                                          return ToolCallPart(type="tool_call", id=self.id, name=self.name, arguments=args)
                                  

                                  Transport

                                  Bases: ABC

                                  Abstract transport for Claude communication.

                                  WARNING: This internal API is exposed for custom transport implementations (e.g., remote Claude Code connections). The Claude Code team may change or or remove this abstract class in any future release. Custom implementations must be updated to match interface changes.

                                  This is a low-level transport interface that handles raw I/O with the Claude process or service. The Query class builds on top of this to implement the control protocol and message routing.

                                  Source code in src/clawd_code_sdk/_internal/transport/__init__.py
                                  class Transport(ABC):
                                      """Abstract transport for Claude communication.
                                  
                                      WARNING: This internal API is exposed for custom transport implementations
                                      (e.g., remote Claude Code connections). The Claude Code team may change or
                                      or remove this abstract class in any future release. Custom implementations
                                      must be updated to match interface changes.
                                  
                                      This is a low-level transport interface that handles raw I/O with the Claude
                                      process or service. The Query class builds on top of this to implement the
                                      control protocol and message routing.
                                      """
                                  
                                      @abstractmethod
                                      async def connect(self) -> None:
                                          """Connect the transport and prepare for communication.
                                  
                                          For subprocess transports, this starts the process.
                                          For network transports, this establishes the connection.
                                          """
                                  
                                      @abstractmethod
                                      async def write(self, data: str) -> None:
                                          """Write raw data to the transport.
                                  
                                          Args:
                                              data: Raw string data to write (typically JSON + newline)
                                          """
                                  
                                      @abstractmethod
                                      def read_messages(self) -> AsyncIterator[dict[str, Any]]:
                                          """Read and parse messages from the transport.
                                  
                                          Yields:
                                              Parsed JSON messages from the transport
                                          """
                                  
                                      @abstractmethod
                                      async def close(self) -> None:
                                          """Close the transport connection and clean up resources."""
                                  
                                      @abstractmethod
                                      async def end_input(self) -> None:
                                          """End the input stream (close stdin for process transports)."""
                                  

                                  close abstractmethod async

                                  close() -> None
                                  

                                  Close the transport connection and clean up resources.

                                  Source code in src/clawd_code_sdk/_internal/transport/__init__.py
                                  @abstractmethod
                                  async def close(self) -> None:
                                      """Close the transport connection and clean up resources."""
                                  

                                  connect abstractmethod async

                                  connect() -> None
                                  

                                  Connect the transport and prepare for communication.

                                  For subprocess transports, this starts the process. For network transports, this establishes the connection.

                                  Source code in src/clawd_code_sdk/_internal/transport/__init__.py
                                  @abstractmethod
                                  async def connect(self) -> None:
                                      """Connect the transport and prepare for communication.
                                  
                                      For subprocess transports, this starts the process.
                                      For network transports, this establishes the connection.
                                      """
                                  

                                  end_input abstractmethod async

                                  end_input() -> None
                                  

                                  End the input stream (close stdin for process transports).

                                  Source code in src/clawd_code_sdk/_internal/transport/__init__.py
                                  @abstractmethod
                                  async def end_input(self) -> None:
                                      """End the input stream (close stdin for process transports)."""
                                  

                                  read_messages abstractmethod

                                  read_messages() -> AsyncIterator[dict[str, Any]]
                                  

                                  Read and parse messages from the transport.

                                  Yields:

                                  Type Description
                                  AsyncIterator[dict[str, Any]]

                                  Parsed JSON messages from the transport

                                  Source code in src/clawd_code_sdk/_internal/transport/__init__.py
                                  @abstractmethod
                                  def read_messages(self) -> AsyncIterator[dict[str, Any]]:
                                      """Read and parse messages from the transport.
                                  
                                      Yields:
                                          Parsed JSON messages from the transport
                                      """
                                  

                                  write abstractmethod async

                                  write(data: str) -> None
                                  

                                  Write raw data to the transport.

                                  Parameters:

                                  Name Type Description Default
                                  data str

                                  Raw string data to write (typically JSON + newline)

                                  required
                                  Source code in src/clawd_code_sdk/_internal/transport/__init__.py
                                  @abstractmethod
                                  async def write(self, data: str) -> None:
                                      """Write raw data to the transport.
                                  
                                      Args:
                                          data: Raw string data to write (typically JSON + newline)
                                      """
                                  

                                  UserDocumentPrompt dataclass

                                  A user prompt containing a base64-encoded PDF document.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  @dataclass
                                  class UserDocumentPrompt:
                                      """A user prompt containing a base64-encoded PDF document."""
                                  
                                      document_data: str
                                      """Base64-encoded PDF data."""
                                      media_type: DocumentMediaType = "application/pdf"
                                      """MIME type of the document."""
                                      title: str | None = None
                                      """Optional document title."""
                                      context: str | None = None
                                      """Optional context about the document."""
                                  
                                      def to_content_block(self) -> BetaRequestDocumentBlockParam:
                                          """Return the Anthropic API content block dict."""
                                          block = BetaRequestDocumentBlockParam(
                                              type="document",
                                              source=BetaBase64PDFSourceParam(
                                                  type="base64",
                                                  media_type=self.media_type,
                                                  data=self.document_data,
                                              ),
                                              title=self.title,
                                              context=self.context,
                                          )
                                          return cast(
                                              "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
                                          )
                                  

                                  context class-attribute instance-attribute

                                  context: str | None = None
                                  

                                  Optional context about the document.

                                  document_data instance-attribute

                                  document_data: str
                                  

                                  Base64-encoded PDF data.

                                  media_type class-attribute instance-attribute

                                  media_type: DocumentMediaType = 'application/pdf'
                                  

                                  MIME type of the document.

                                  title class-attribute instance-attribute

                                  title: str | None = None
                                  

                                  Optional document title.

                                  to_content_block

                                  to_content_block() -> BetaRequestDocumentBlockParam
                                  

                                  Return the Anthropic API content block dict.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  def to_content_block(self) -> BetaRequestDocumentBlockParam:
                                      """Return the Anthropic API content block dict."""
                                      block = BetaRequestDocumentBlockParam(
                                          type="document",
                                          source=BetaBase64PDFSourceParam(
                                              type="base64",
                                              media_type=self.media_type,
                                              data=self.document_data,
                                          ),
                                          title=self.title,
                                          context=self.context,
                                      )
                                      return cast(
                                          "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
                                      )
                                  

                                  UserDocumentURLPrompt dataclass

                                  A user prompt containing a PDF document referenced by URL.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  @dataclass
                                  class UserDocumentURLPrompt:
                                      """A user prompt containing a PDF document referenced by URL."""
                                  
                                      url: str
                                      """Public URL of the PDF document."""
                                      title: str | None = None
                                      """Optional document title."""
                                      context: str | None = None
                                      """Optional context about the document."""
                                  
                                      def to_content_block(self) -> BetaRequestDocumentBlockParam:
                                          """Return the Anthropic API content block dict."""
                                          block = BetaRequestDocumentBlockParam(
                                              type="document",
                                              source=BetaURLPDFSourceParam(type="url", url=self.url),
                                              title=self.title,
                                              context=self.context,
                                          )
                                          return cast(
                                              "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
                                          )
                                  

                                  context class-attribute instance-attribute

                                  context: str | None = None
                                  

                                  Optional context about the document.

                                  title class-attribute instance-attribute

                                  title: str | None = None
                                  

                                  Optional document title.

                                  url instance-attribute

                                  url: str
                                  

                                  Public URL of the PDF document.

                                  to_content_block

                                  to_content_block() -> BetaRequestDocumentBlockParam
                                  

                                  Return the Anthropic API content block dict.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  def to_content_block(self) -> BetaRequestDocumentBlockParam:
                                      """Return the Anthropic API content block dict."""
                                      block = BetaRequestDocumentBlockParam(
                                          type="document",
                                          source=BetaURLPDFSourceParam(type="url", url=self.url),
                                          title=self.title,
                                          context=self.context,
                                      )
                                      return cast(
                                          "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
                                      )
                                  

                                  UserImagePrompt dataclass

                                  A user prompt containing a single base64-encoded image.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  @dataclass
                                  class UserImagePrompt:
                                      """A user prompt containing a single base64-encoded image."""
                                  
                                      image_data: str
                                      """Base64-encoded image data."""
                                      media_type: ImageMediaType
                                      """MIME type of the image."""
                                  
                                      def to_content_block(self) -> BetaImageBlockParam:
                                          """Return the Anthropic API content block dict."""
                                          return BetaImageBlockParam(
                                              type="image",
                                              source=BetaBase64ImageSourceParam(
                                                  type="base64",
                                                  media_type=self.media_type,
                                                  data=self.image_data,
                                              ),
                                          )
                                  

                                  image_data instance-attribute

                                  image_data: str
                                  

                                  Base64-encoded image data.

                                  media_type instance-attribute

                                  media_type: ImageMediaType
                                  

                                  MIME type of the image.

                                  to_content_block

                                  to_content_block() -> BetaImageBlockParam
                                  

                                  Return the Anthropic API content block dict.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  def to_content_block(self) -> BetaImageBlockParam:
                                      """Return the Anthropic API content block dict."""
                                      return BetaImageBlockParam(
                                          type="image",
                                          source=BetaBase64ImageSourceParam(
                                              type="base64",
                                              media_type=self.media_type,
                                              data=self.image_data,
                                          ),
                                      )
                                  

                                  UserImageURLPrompt dataclass

                                  A user prompt containing an image referenced by URL.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  @dataclass
                                  class UserImageURLPrompt:
                                      """A user prompt containing an image referenced by URL."""
                                  
                                      url: str
                                      """Public URL of the image."""
                                  
                                      def to_content_block(self) -> BetaImageBlockParam:
                                          """Return the Anthropic API content block dict."""
                                          return BetaImageBlockParam(
                                              type="image",
                                              source=BetaURLImageSourceParam(type="url", url=self.url),
                                          )
                                  

                                  url instance-attribute

                                  url: str
                                  

                                  Public URL of the image.

                                  to_content_block

                                  to_content_block() -> BetaImageBlockParam
                                  

                                  Return the Anthropic API content block dict.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  def to_content_block(self) -> BetaImageBlockParam:
                                      """Return the Anthropic API content block dict."""
                                      return BetaImageBlockParam(
                                          type="image",
                                          source=BetaURLImageSourceParam(type="url", url=self.url),
                                      )
                                  

                                  UserMessage

                                  Bases: BaseModel

                                  User message.

                                  Source code in src/clawd_code_sdk/models/messages.py
                                  class UserMessage(BaseModel):
                                      """User message."""
                                  
                                      model_config = ConfigDict(
                                          extra="forbid" if IS_DEV else "ignore", arbitrary_types_allowed=True, populate_by_name=True
                                      )
                                      type: Literal["user"] = "user"
                                      uuid: str | None = None
                                      """Always set for incoming user messages, can be omitted for objects created in query()."""
                                      session_id: str | None = None
                                      parent_tool_use_id: str | None = None
                                      tool_use_result: (
                                          Sequence[ToolUseResult | dict[str, Any]] | ToolUseResult | dict[str, Any] | str | None
                                      ) = None
                                      is_replay: bool | None = Field(default=None, validation_alias="isReplay")
                                      is_synthetic: bool | None = Field(default=None, validation_alias="isSynthetic")
                                      priority: MessagePriority | None = None
                                      message: MessageParam
                                      timestamp: str | None = None
                                      file_attachments: list[FileAttachment] | None = None
                                      origin: SDKMessageOrigin | None = None
                                      should_query: bool | None = Field(default=None, validation_alias="shouldQuery")
                                      client_composed: bool | None = None
                                      """Set when the host composed this message (as opposed to the user typing it)."""
                                      pasted_content: list[Any] | None = None
                                      inline_pastes: list[str] | None = None
                                      agent_id: str | None = None
                                      """Subagent ID when this message belongs to a subagent transcript."""
                                      subagent_type: str | None = None
                                      task_description: str | None = None
                                      tool_result_meta: list[ToolResultMeta] | None = None
                                      """Per-tool-result metadata, e.g. how permission was decided (undocumented)."""
                                  
                                      @property
                                      def content(self) -> str | Sequence[UserContentBlock]:
                                          """Return the message content."""
                                          return self.message.content
                                  
                                      def parse_command_output(self) -> str | None:
                                          """Extract output from legacy XML-tagged command output in user messages."""
                                          content = self.content if isinstance(self.content, str) else ""
                                          pattern = r"<local-command-(?:stdout|stderr)>(.*?)</local-command-(?:stdout|stderr)>"
                                          match = re.search(pattern, content, re.DOTALL)
                                          return match.group(1) if match else None
                                  

                                  agent_id class-attribute instance-attribute

                                  agent_id: str | None = None
                                  

                                  Subagent ID when this message belongs to a subagent transcript.

                                  client_composed class-attribute instance-attribute

                                  client_composed: bool | None = None
                                  

                                  Set when the host composed this message (as opposed to the user typing it).

                                  content property

                                  content: str | Sequence[UserContentBlock]
                                  

                                  Return the message content.

                                  tool_result_meta class-attribute instance-attribute

                                  tool_result_meta: list[ToolResultMeta] | None = None
                                  

                                  Per-tool-result metadata, e.g. how permission was decided (undocumented).

                                  uuid class-attribute instance-attribute

                                  uuid: str | None = None
                                  

                                  Always set for incoming user messages, can be omitted for objects created in query().

                                  parse_command_output

                                  parse_command_output() -> str | None
                                  

                                  Extract output from legacy XML-tagged command output in user messages.

                                  Source code in src/clawd_code_sdk/models/messages.py
                                  def parse_command_output(self) -> str | None:
                                      """Extract output from legacy XML-tagged command output in user messages."""
                                      content = self.content if isinstance(self.content, str) else ""
                                      pattern = r"<local-command-(?:stdout|stderr)>(.*?)</local-command-(?:stdout|stderr)>"
                                      match = re.search(pattern, content, re.DOTALL)
                                      return match.group(1) if match else None
                                  

                                  UserPlainTextDocumentPrompt dataclass

                                  A user prompt containing a plain text document.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  @dataclass
                                  class UserPlainTextDocumentPrompt:
                                      """A user prompt containing a plain text document."""
                                  
                                      data: str
                                      """The plain text content."""
                                      media_type: PlainTextMediaType = "text/plain"
                                      """MIME type (always text/plain)."""
                                      title: str | None = None
                                      """Optional document title."""
                                      context: str | None = None
                                      """Optional context about the document."""
                                  
                                      def to_content_block(self) -> BetaRequestDocumentBlockParam:
                                          """Return the Anthropic API content block dict."""
                                          block = BetaRequestDocumentBlockParam(
                                              type="document",
                                              source=BetaPlainTextSourceParam(
                                                  type="text",
                                                  media_type=self.media_type,
                                                  data=self.data,
                                              ),
                                              title=self.title,
                                              context=self.context,
                                          )
                                          return cast(
                                              "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
                                          )
                                  

                                  context class-attribute instance-attribute

                                  context: str | None = None
                                  

                                  Optional context about the document.

                                  data instance-attribute

                                  data: str
                                  

                                  The plain text content.

                                  media_type class-attribute instance-attribute

                                  media_type: PlainTextMediaType = 'text/plain'
                                  

                                  MIME type (always text/plain).

                                  title class-attribute instance-attribute

                                  title: str | None = None
                                  

                                  Optional document title.

                                  to_content_block

                                  to_content_block() -> BetaRequestDocumentBlockParam
                                  

                                  Return the Anthropic API content block dict.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  def to_content_block(self) -> BetaRequestDocumentBlockParam:
                                      """Return the Anthropic API content block dict."""
                                      block = BetaRequestDocumentBlockParam(
                                          type="document",
                                          source=BetaPlainTextSourceParam(
                                              type="text",
                                              media_type=self.media_type,
                                              data=self.data,
                                          ),
                                          title=self.title,
                                          context=self.context,
                                      )
                                      return cast(
                                          "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
                                      )
                                  

                                  UserPromptSubmitHookInput

                                  Bases: BaseHookInput

                                  Input data for UserPromptSubmit hook events.

                                  Source code in src/clawd_code_sdk/models/hooks.py
                                  class UserPromptSubmitHookInput(BaseHookInput):
                                      """Input data for UserPromptSubmit hook events."""
                                  
                                      hook_event_name: Literal["UserPromptSubmit"]
                                      prompt: str
                                      session_title: NotRequired[str]
                                  

                                  UserTextPrompt dataclass

                                  A text-only user prompt.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  @dataclass
                                  class UserTextPrompt:
                                      """A text-only user prompt."""
                                  
                                      text: str
                                  
                                      def to_content_block(self) -> BetaTextBlockParam:
                                          """Return the Anthropic API content block dict."""
                                          return BetaTextBlockParam(type="text", text=self.text)
                                  

                                  to_content_block

                                  to_content_block() -> BetaTextBlockParam
                                  

                                  Return the Anthropic API content block dict.

                                  Source code in src/clawd_code_sdk/models/prompts.py
                                  def to_content_block(self) -> BetaTextBlockParam:
                                      """Return the Anthropic API content block dict."""
                                      return BetaTextBlockParam(type="text", text=self.text)
                                  

                                  create_sdk_mcp_server

                                  create_sdk_mcp_server(
                                      name: str, version: str = "1.0.0", tools: list[SdkMcpTool[Any]] | None = None
                                  ) -> McpSdkServerConfigWithInstance
                                  

                                  Create an in-process MCP server that runs within your Python application.

                                  Unlike external MCP servers that run as separate processes, SDK MCP servers run directly in your application's process. This provides: - Better performance (no IPC overhead) - Simpler deployment (single process) - Easier debugging (same process) - Direct access to your application's state

                                  Parameters:

                                  Name Type Description Default
                                  name str

                                  Unique identifier for the server. This name is used to reference the server in the mcp_servers configuration.

                                  required
                                  version str

                                  Server version string. Defaults to "1.0.0". This is for informational purposes and doesn't affect functionality.

                                  '1.0.0'
                                  tools list[SdkMcpTool[Any]] | None

                                  List of SdkMcpTool instances created with the @tool decorator. These are the functions that Claude can call through this server. If None or empty, the server will have no tools (rarely useful).

                                  None

                                  Returns:

                                  Name Type Description
                                  McpSdkServerConfigWithInstance McpSdkServerConfigWithInstance

                                  A configuration object that can be passed to

                                  McpSdkServerConfigWithInstance

                                  ClaudeAgentOptions.mcp_servers. Its instance is a regular

                                  McpSdkServerConfigWithInstance

                                  mcp.server.Server that the SDK connects to Claude Code over an

                                  McpSdkServerConfigWithInstance

                                  in-memory MCP transport.

                                  Example

                                  Simple calculator server:

                                  @tool("add", "Add numbers", {"a": float, "b": float}) ... async def add(args): ... return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}

                                  calculator = create_sdk_mcp_server(name="calculator", tools=[add]) options = ClaudeAgentOptions(mcp_servers={"calc": calculator})

                                  Bringing your own server: any mcp.server.Server built with the installed mcp package can be used in place of this helper, and the requests it handles (tools, resources, prompts, ...) are served. Requests and notifications the server sends to the client (sampling, elicitation, roots, logging, progress, list_changed) are not forwarded:

                                  from mcp.server import Server my_server = Server("mine") # register handlers with the mcp API config = McpSdkServerConfigWithInstance(name="mine", instance=my_server)

                                  Notes
                                  • Tool arguments are validated against the tool's input schema. Unknown tools, invalid arguments and exceptions raised by a handler are all reported to Claude as error results rather than failing the request.
                                  • Works with both mcp 1.x and mcp 2.x.
                                  Source code in src/clawd_code_sdk/mcp_utils.py
                                  def create_sdk_mcp_server(
                                      name: str,
                                      version: str = "1.0.0",
                                      tools: list[SdkMcpTool[Any]] | None = None,
                                  ) -> McpSdkServerConfigWithInstance:
                                      """Create an in-process MCP server that runs within your Python application.
                                  
                                      Unlike external MCP servers that run as separate processes, SDK MCP servers
                                      run directly in your application's process. This provides:
                                      - Better performance (no IPC overhead)
                                      - Simpler deployment (single process)
                                      - Easier debugging (same process)
                                      - Direct access to your application's state
                                  
                                      Args:
                                          name: Unique identifier for the server. This name is used to reference
                                              the server in the mcp_servers configuration.
                                          version: Server version string. Defaults to "1.0.0". This is for
                                              informational purposes and doesn't affect functionality.
                                          tools: List of SdkMcpTool instances created with the @tool decorator.
                                              These are the functions that Claude can call through this server.
                                              If None or empty, the server will have no tools (rarely useful).
                                  
                                      Returns:
                                          McpSdkServerConfigWithInstance: A configuration object that can be passed to
                                          ClaudeAgentOptions.mcp_servers. Its ``instance`` is a regular
                                          ``mcp.server.Server`` that the SDK connects to Claude Code over an
                                          in-memory MCP transport.
                                  
                                      Example:
                                          Simple calculator server:
                                          >>> @tool("add", "Add numbers", {"a": float, "b": float})
                                          ... async def add(args):
                                          ...     return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}
                                          >>>
                                          >>> calculator = create_sdk_mcp_server(name="calculator", tools=[add])
                                          >>> options = ClaudeAgentOptions(mcp_servers={"calc": calculator})
                                  
                                          Bringing your own server: any ``mcp.server.Server`` built with the
                                          installed ``mcp`` package can be used in place of this helper, and the
                                          requests it handles (tools, resources, prompts, ...) are served.
                                          Requests and notifications the server sends to the client (sampling,
                                          elicitation, roots, logging, progress, list_changed) are not forwarded:
                                          >>> from mcp.server import Server
                                          >>> my_server = Server("mine")  # register handlers with the mcp API
                                          >>> config = McpSdkServerConfigWithInstance(name="mine", instance=my_server)
                                  
                                      Notes:
                                          - Tool arguments are validated against the tool's input schema. Unknown
                                            tools, invalid arguments and exceptions raised by a handler are all
                                            reported to Claude as error results rather than failing the request.
                                          - Works with both mcp 1.x and mcp 2.x.
                                      """
                                      tool_defs = tools or []
                                      tools_by_name = {tool_def.name: tool_def for tool_def in tool_defs}
                                      schemas = {tool_def.name: build_input_schema(tool_def.input_schema) for tool_def in tool_defs}
                                      wire_tools = [
                                          Tool.model_validate({
                                              "name": tool_def.name,
                                              "title": tool_def.title,
                                              "description": tool_def.description,
                                              "inputSchema": schemas[tool_def.name],
                                              "outputSchema": tool_def.output_schema,
                                              "annotations": tool_def.annotations,
                                              "_meta": build_tool_meta(tool_def),
                                          })
                                          for tool_def in tool_defs
                                      ]
                                  
                                      async def run_tool(tool_name: str, arguments: dict[str, Any]) -> CallToolResult:
                                          # The SDK owns these semantics so a tool behaves the same on every
                                          # supported mcp version: unknown tools, invalid arguments and handler
                                          # failures all come back as isError results the model can read, never
                                          # as protocol errors.
                                          tool_def = tools_by_name.get(tool_name)
                                          if tool_def is None:
                                              return _tool_error_result(f"Tool '{tool_name}' not found")
                                          try:
                                              try:
                                                  jsonschema.validate(instance=arguments, schema=schemas[tool_name])
                                              except jsonschema.ValidationError as e:
                                                  return _tool_error_result(f"Input validation error: {e.message}")
                                              result = await tool_def.handler(arguments)
                                              return CallToolResult.model_validate({
                                                  "content": convert_tool_content(result.get("content", [])),
                                                  "isError": bool(result.get("is_error", False)),
                                              })
                                          except Exception as e:
                                              return _tool_error_result(str(e))
                                  
                                      server = build_tool_server(name, version, wire_tools, run_tool)
                                      return McpSdkServerConfigWithInstance(name=name, instance=server)
                                  

                                  delete_session

                                  delete_session(session_id: str, directory: str | None = None) -> None
                                  

                                  Delete a session by removing its JSONL file and subagent transcripts.

                                  This is a hard delete — the {session_id}.jsonl file is removed permanently, along with the sibling {session_id}/ subdirectory that holds subagent transcripts (if it exists). SDK users who need soft-delete semantics can use tag_session(id, '__hidden') and filter on listing instead.

                                  Parameters:

                                  Name Type Description Default
                                  session_id str

                                  UUID of the session to delete.

                                  required
                                  directory str | None

                                  Project directory path (same semantics as list_sessions(directory=...)). When omitted, all project directories are searched for the session file.

                                  None

                                  Raises:

                                  Type Description
                                  ValueError

                                  If session_id is not a valid UUID.

                                  FileNotFoundError

                                  If the session file cannot be found.

                                  Example

                                  Delete a session::

                                  delete_session("550e8400-e29b-41d4-a716-446655440000")
                                  
                                  Source code in src/clawd_code_sdk/_internal/session_mutations.py
                                  def delete_session(
                                      session_id: str,
                                      directory: str | None = None,
                                  ) -> None:
                                      """Delete a session by removing its JSONL file and subagent transcripts.
                                  
                                      This is a hard delete — the ``{session_id}.jsonl`` file is removed
                                      permanently, along with the sibling ``{session_id}/`` subdirectory that
                                      holds subagent transcripts (if it exists). SDK users who need soft-delete
                                      semantics can use ``tag_session(id, '__hidden')`` and filter on listing
                                      instead.
                                  
                                      Args:
                                          session_id: UUID of the session to delete.
                                          directory: Project directory path (same semantics as
                                              ``list_sessions(directory=...)``). When omitted, all project
                                              directories are searched for the session file.
                                  
                                      Raises:
                                          ValueError: If ``session_id`` is not a valid UUID.
                                          FileNotFoundError: If the session file cannot be found.
                                  
                                      Example:
                                          Delete a session::
                                  
                                              delete_session("550e8400-e29b-41d4-a716-446655440000")
                                      """
                                      if not _validate_uuid(session_id):
                                          raise ValueError(f"Invalid session_id: {session_id}")
                                  
                                      path = _find_session_file(session_id, directory)
                                      if path is None:
                                          raise FileNotFoundError(
                                              f"Session {session_id} not found"
                                              + (f" in project directory for {directory}" if directory else "")
                                          )
                                      try:
                                          path.unlink()
                                      except OSError as e:
                                          if e.errno == errno.ENOENT:
                                              raise FileNotFoundError(f"Session {session_id} not found") from e
                                          raise
                                      # Subagent transcripts live in a sibling {session_id}/ dir; often absent.
                                      shutil.rmtree(path.parent / session_id, ignore_errors=True)
                                  

                                  fork_session

                                  fork_session(
                                      session_id: str,
                                      directory: str | None = None,
                                      up_to_message_id: str | None = None,
                                      title: str | None = None,
                                  ) -> ForkSessionResult
                                  

                                  Fork a session into a new branch with fresh UUIDs.

                                  Copies transcript messages from the source session into a new session file, remapping every message UUID and preserving the parentUuid chain. Supports up_to_message_id for branching from a specific point in the conversation.

                                  Forked sessions start without undo history (file-history snapshots are not copied).

                                  Parameters:

                                  Name Type Description Default
                                  session_id str

                                  UUID of the source session to fork.

                                  required
                                  directory str | None

                                  Project directory path (same semantics as list_sessions(directory=...)). When omitted, all project directories are searched for the session file.

                                  None
                                  up_to_message_id str | None

                                  Slice transcript up to this message UUID (inclusive). If omitted, copies the full transcript.

                                  None
                                  title str | None

                                  Custom title for the fork. If omitted, derives from the original title + " (fork)".

                                  None

                                  Returns:

                                  Type Description
                                  ForkSessionResult

                                  ForkSessionResult with the new session's UUID.

                                  Raises:

                                  Type Description
                                  ValueError

                                  If session_id or up_to_message_id is not a valid UUID.

                                  FileNotFoundError

                                  If the source session file cannot be found.

                                  ValueError

                                  If the session has no messages to fork, or if up_to_message_id is not found in the transcript.

                                  Example

                                  Fork a session::

                                  result = fork_session("550e8400-e29b-41d4-a716-446655440000")
                                  print(result.session_id)
                                  

                                  Fork from a specific point::

                                  result = fork_session(
                                      "550e8400-e29b-41d4-a716-446655440000",
                                      up_to_message_id="660e8400-e29b-41d4-a716-446655440001",
                                  )
                                  
                                  Source code in src/clawd_code_sdk/_internal/session_mutations.py
                                  def fork_session(
                                      session_id: str,
                                      directory: str | None = None,
                                      up_to_message_id: str | None = None,
                                      title: str | None = None,
                                  ) -> ForkSessionResult:
                                      """Fork a session into a new branch with fresh UUIDs.
                                  
                                      Copies transcript messages from the source session into a new session
                                      file, remapping every message UUID and preserving the ``parentUuid``
                                      chain. Supports ``up_to_message_id`` for branching from a specific
                                      point in the conversation.
                                  
                                      Forked sessions start without undo history (file-history snapshots are
                                      not copied).
                                  
                                      Args:
                                          session_id: UUID of the source session to fork.
                                          directory: Project directory path (same semantics as
                                              ``list_sessions(directory=...)``). When omitted, all project
                                              directories are searched for the session file.
                                          up_to_message_id: Slice transcript up to this message UUID
                                              (inclusive). If omitted, copies the full transcript.
                                          title: Custom title for the fork. If omitted, derives from
                                              the original title + " (fork)".
                                  
                                      Returns:
                                          ``ForkSessionResult`` with the new session's UUID.
                                  
                                      Raises:
                                          ValueError: If ``session_id`` or ``up_to_message_id`` is not a
                                              valid UUID.
                                          FileNotFoundError: If the source session file cannot be found.
                                          ValueError: If the session has no messages to fork, or if
                                              ``up_to_message_id`` is not found in the transcript.
                                  
                                      Example:
                                          Fork a session::
                                  
                                              result = fork_session("550e8400-e29b-41d4-a716-446655440000")
                                              print(result.session_id)
                                  
                                          Fork from a specific point::
                                  
                                              result = fork_session(
                                                  "550e8400-e29b-41d4-a716-446655440000",
                                                  up_to_message_id="660e8400-e29b-41d4-a716-446655440001",
                                              )
                                      """
                                      if not _validate_uuid(session_id):
                                          raise ValueError(f"Invalid session_id: {session_id}")
                                      if up_to_message_id and not _validate_uuid(up_to_message_id):
                                          raise ValueError(f"Invalid up_to_message_id: {up_to_message_id}")
                                  
                                      source = _find_session_file_with_dir(session_id, directory)
                                      if source is None:
                                          raise FileNotFoundError(
                                              f"Session {session_id} not found"
                                              + (f" in project directory for {directory}" if directory else "")
                                          )
                                      file_path, project_dir = source
                                  
                                      content = file_path.read_bytes()
                                      if not content:
                                          raise ValueError(f"Session {session_id} has no messages to fork")
                                  
                                      transcript, content_replacements = _parse_fork_transcript(content, session_id)
                                  
                                      # Filter out sidechains (subagent sessions with separate parentUuid
                                      # graphs). Keep isMeta entries — they're interleaved in the main chain.
                                      transcript = [e for e in transcript if not e.get("isSidechain")]
                                  
                                      if not transcript:
                                          raise ValueError(f"Session {session_id} has no messages to fork")
                                  
                                      if up_to_message_id:
                                          cutoff = -1
                                          for i, entry in enumerate(transcript):
                                              if entry.get("uuid") == up_to_message_id:
                                                  cutoff = i
                                                  break
                                          if cutoff == -1:
                                              raise ValueError(f"Message {up_to_message_id} not found in session {session_id}")
                                          transcript = transcript[: cutoff + 1]
                                  
                                      # Include progress entries in the mapping — needed for parentUuid chain walk.
                                      uuid_mapping: dict[str, str] = {}
                                      for entry in transcript:
                                          uuid_mapping[entry["uuid"]] = str(uuid_mod.uuid4())
                                  
                                      # Filter out progress messages from written output. They're UI-only
                                      # chain links; not needed in a fresh fork.
                                      writable = [e for e in transcript if e.get("type") != "progress"]
                                      if not writable:
                                          raise ValueError(f"Session {session_id} has no messages to fork")
                                  
                                      by_uuid: dict[str, dict[str, Any]] = {}
                                      for entry in transcript:
                                          by_uuid[entry["uuid"]] = entry
                                  
                                      forked_session_id = str(uuid_mod.uuid4())
                                  
                                      now = datetime.now(UTC).isoformat().replace("+00:00", "Z")
                                      lines: list[str] = []
                                  
                                      for i, original in enumerate(writable):
                                          new_uuid = uuid_mapping[original["uuid"]]
                                  
                                          # Resolve parentUuid, skipping progress ancestors.
                                          new_parent_uuid: str | None = None
                                          parent_id: str | None = original.get("parentUuid")
                                          while parent_id:
                                              parent = by_uuid.get(parent_id)
                                              if not parent:
                                                  break
                                              if parent.get("type") != "progress":
                                                  new_parent_uuid = uuid_mapping.get(parent_id)
                                                  break
                                              parent_id = parent.get("parentUuid")
                                  
                                          # Only update timestamp on the last message (leaf detection on resume).
                                          timestamp = now if i == len(writable) - 1 else original.get("timestamp", now)
                                  
                                          # Remap logicalParentUuid (compact-boundary backpointer).
                                          logical_parent = original.get("logicalParentUuid")
                                          new_logical_parent = uuid_mapping.get(logical_parent) if logical_parent else logical_parent
                                  
                                          forked = {
                                              **original,
                                              "uuid": new_uuid,
                                              "parentUuid": new_parent_uuid,
                                              "logicalParentUuid": new_logical_parent,
                                              "sessionId": forked_session_id,
                                              "timestamp": timestamp,
                                              # Clear session-specific fields from the spread
                                              "isSidechain": False,
                                              "forkedFrom": {
                                                  "sessionId": session_id,
                                                  "messageUuid": original["uuid"],
                                              },
                                          }
                                          # Remove fields that would leak state from the source session
                                          for key in ("teamName", "agentName", "slug", "sourceToolAssistantUUID"):
                                              forked.pop(key, None)
                                  
                                          lines.append(json.dumps(forked, separators=(",", ":")))
                                  
                                      # Append content-replacement entry (if any) with the fork's sessionId.
                                      if content_replacements:
                                          lines.append(
                                              json.dumps(
                                                  {
                                                      "type": "content-replacement",
                                                      "sessionId": forked_session_id,
                                                      "replacements": content_replacements,
                                                  },
                                                  separators=(",", ":"),
                                              )
                                          )
                                  
                                      # Derive title: explicit > original customTitle/aiTitle > first prompt.
                                      fork_title = title.strip() if title else None
                                      if not fork_title:
                                          buf_len = len(content)
                                          head = content[: min(buf_len, LITE_READ_BUF_SIZE)].decode("utf-8", errors="replace")
                                          tail = content[max(0, buf_len - LITE_READ_BUF_SIZE) :].decode("utf-8", errors="replace")
                                          base = (
                                              _extract_last_json_string_field(tail, "customTitle")
                                              or _extract_last_json_string_field(head, "customTitle")
                                              or _extract_last_json_string_field(tail, "aiTitle")
                                              or _extract_last_json_string_field(head, "aiTitle")
                                              or _extract_first_prompt_from_head(head)
                                              or "Forked session"
                                          )
                                          fork_title = f"{base} (fork)"
                                  
                                      lines.append(
                                          json.dumps(
                                              {
                                                  "type": "custom-title",
                                                  "sessionId": forked_session_id,
                                                  "customTitle": fork_title,
                                              },
                                              separators=(",", ":"),
                                          )
                                      )
                                  
                                      fork_path = project_dir / f"{forked_session_id}.jsonl"
                                      fd = os.open(fork_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
                                      try:
                                          os.write(fd, ("\n".join(lines) + "\n").encode("utf-8"))
                                      finally:
                                          os.close(fd)
                                  
                                      return ForkSessionResult(session_id=forked_session_id)
                                  

                                  get_session_info

                                  get_session_info(session_id: str, directory: str | None = None) -> SDKSessionInfo | None
                                  

                                  Reads metadata for a single session by ID.

                                  Wraps _read_session_lite for one file — no O(n) directory scan. Directory resolution matches get_session_messages: directory is the project path; when omitted, all project directories are searched for the session file.

                                  Parameters:

                                  Name Type Description Default
                                  session_id str

                                  UUID of the session to look up.

                                  required
                                  directory str | None

                                  Project directory path (same semantics as list_sessions(directory=...)). When omitted, all project directories are searched for the session file.

                                  None

                                  Returns:

                                  Type Description
                                  SDKSessionInfo | None

                                  SDKSessionInfo for the session, or None if the session file

                                  SDKSessionInfo | None

                                  is not found, is a sidechain session, or has no extractable summary.

                                  Source code in src/clawd_code_sdk/_internal/sessions.py
                                  def get_session_info(session_id: str, directory: str | None = None) -> SDKSessionInfo | None:
                                      """Reads metadata for a single session by ID.
                                  
                                      Wraps ``_read_session_lite`` for one file — no O(n) directory scan.
                                      Directory resolution matches ``get_session_messages``: ``directory`` is
                                      the project path; when omitted, all project directories are searched for
                                      the session file.
                                  
                                      Args:
                                          session_id: UUID of the session to look up.
                                          directory: Project directory path (same semantics as
                                              ``list_sessions(directory=...)``). When omitted, all project
                                              directories are searched for the session file.
                                  
                                      Returns:
                                          ``SDKSessionInfo`` for the session, or ``None`` if the session file
                                          is not found, is a sidechain session, or has no extractable summary.
                                      """
                                      uuid = _validate_uuid(session_id)
                                      if not uuid:
                                          return None
                                      file_name = f"{uuid}.jsonl"
                                  
                                      if directory:
                                          canonical = _canonicalize_path(directory)
                                          project_dir = _find_project_dir(canonical)
                                          if project_dir and (lite := _read_session_lite(project_dir / file_name)):
                                              return _parse_session_info_from_lite(uuid, lite, canonical)
                                          # Worktree fallback — matches get_session_messages semantics.
                                          # Sessions may live under a different worktree root.
                                          for wt in _get_worktree_paths(canonical):
                                              if wt == canonical:
                                                  continue
                                              wt_project_dir = _find_project_dir(wt)
                                              if wt_project_dir and (lite := _read_session_lite(wt_project_dir / file_name)):
                                                  return _parse_session_info_from_lite(uuid, lite, wt)
                                  
                                          return None
                                  
                                      # No directory — search all project directories for the session file.
                                      projects_dir = _get_projects_dir()
                                      try:
                                          dirents = [e for e in projects_dir.iterdir() if e.is_dir()]
                                      except OSError:
                                          return None
                                      for entry in dirents:
                                          lite = _read_session_lite(entry / file_name)
                                          if lite is not None:
                                              return _parse_session_info_from_lite(uuid, lite)
                                      return None
                                  

                                  get_session_messages

                                  get_session_messages(
                                      session_id: str, directory: str | None = None, limit: int | None = None, offset: int = 0
                                  ) -> list[SessionMessage]
                                  

                                  Reads a session's conversation messages from its JSONL transcript file.

                                  Parses the full JSONL, builds the conversation chain via parentUuid links, and returns user/assistant messages in chronological order.

                                  Parameters:

                                  Name Type Description Default
                                  session_id str

                                  UUID of the session to read.

                                  required
                                  directory str | None

                                  Project directory to find the session in. If omitted, searches all project directories under ~/.claude/projects/.

                                  None
                                  limit int | None

                                  Maximum number of messages to return.

                                  None
                                  offset int

                                  Number of messages to skip from the start.

                                  0

                                  Returns:

                                  Type Description
                                  list[SessionMessage]

                                  List of SessionMessage objects in chronological order. Returns

                                  list[SessionMessage]

                                  an empty list if the session is not found, the session_id is not a

                                  list[SessionMessage]

                                  valid UUID, or the transcript contains no visible messages.

                                  Source code in src/clawd_code_sdk/_internal/sessions.py
                                  def get_session_messages(
                                      session_id: str,
                                      directory: str | None = None,
                                      limit: int | None = None,
                                      offset: int = 0,
                                  ) -> list[SessionMessage]:
                                      """Reads a session's conversation messages from its JSONL transcript file.
                                  
                                      Parses the full JSONL, builds the conversation chain via ``parentUuid``
                                      links, and returns user/assistant messages in chronological order.
                                  
                                      Args:
                                          session_id: UUID of the session to read.
                                          directory: Project directory to find the session in. If omitted,
                                              searches all project directories under ``~/.claude/projects/``.
                                          limit: Maximum number of messages to return.
                                          offset: Number of messages to skip from the start.
                                  
                                      Returns:
                                          List of ``SessionMessage`` objects in chronological order. Returns
                                          an empty list if the session is not found, the session_id is not a
                                          valid UUID, or the transcript contains no visible messages.
                                      """
                                      if not _validate_uuid(session_id):
                                          return []
                                  
                                      content = _read_session_file(session_id, directory)
                                      if not content:
                                          return []
                                  
                                      entries = _parse_transcript_entries(content)
                                      chain = _build_conversation_chain(entries)
                                      visible = [e for e in chain if _is_visible_message(e)]
                                      messages = [_to_session_message(e) for e in visible]
                                  
                                      # Apply offset and limit
                                      if limit is not None and limit > 0:
                                          return messages[offset : offset + limit]
                                      if offset > 0:
                                          return messages[offset:]
                                      return messages
                                  

                                  get_subagent_messages

                                  get_subagent_messages(
                                      session_id: str,
                                      agent_id: str,
                                      directory: str | None = None,
                                      limit: int | None = None,
                                      offset: int = 0,
                                  ) -> list[SessionMessage]
                                  

                                  Reads a subagent's conversation messages from its JSONL transcript file.

                                  Parses the subagent transcript, builds the conversation chain via parentUuid links, and returns user/assistant messages in chronological order. Each message's parent_tool_use_id is the id of the Agent tool_use in the parent session that spawned this subagent (and parent_agent_id the spawning subagent, for nested subagents), read from the agent-<agentId>.meta.json sidecar next to the transcript; both are None if the sidecar is missing or unusable.

                                  Parameters:

                                  Name Type Description Default
                                  session_id str

                                  UUID of the parent session.

                                  required
                                  agent_id str

                                  ID of the subagent (as returned by list_subagents).

                                  required
                                  directory str | None

                                  Project directory to find the session in. If omitted, searches all project directories under ~/.claude/projects/.

                                  None
                                  limit int | None

                                  Maximum number of messages to return.

                                  None
                                  offset int

                                  Number of messages to skip from the start.

                                  0

                                  Returns:

                                  Type Description
                                  list[SessionMessage]

                                  List of SessionMessage objects in chronological order. Returns

                                  list[SessionMessage]

                                  an empty list if the session or subagent is not found, the

                                  list[SessionMessage]

                                  session_id is not a valid UUID, or the transcript contains no

                                  list[SessionMessage]

                                  user/assistant messages.

                                  Source code in src/clawd_code_sdk/_internal/sessions.py
                                  def get_subagent_messages(
                                      session_id: str,
                                      agent_id: str,
                                      directory: str | None = None,
                                      limit: int | None = None,
                                      offset: int = 0,
                                  ) -> list[SessionMessage]:
                                      """Reads a subagent's conversation messages from its JSONL transcript file.
                                  
                                      Parses the subagent transcript, builds the conversation chain via
                                      ``parentUuid`` links, and returns user/assistant messages in
                                      chronological order. Each message's ``parent_tool_use_id`` is the id of
                                      the Agent ``tool_use`` in the parent session that spawned this subagent
                                      (and ``parent_agent_id`` the spawning subagent, for nested subagents),
                                      read from the ``agent-<agentId>.meta.json`` sidecar next to the
                                      transcript; both are ``None`` if the sidecar is missing or unusable.
                                  
                                      Args:
                                          session_id: UUID of the parent session.
                                          agent_id: ID of the subagent (as returned by ``list_subagents``).
                                          directory: Project directory to find the session in. If omitted,
                                              searches all project directories under ``~/.claude/projects/``.
                                          limit: Maximum number of messages to return.
                                          offset: Number of messages to skip from the start.
                                  
                                      Returns:
                                          List of ``SessionMessage`` objects in chronological order. Returns
                                          an empty list if the session or subagent is not found, the
                                          session_id is not a valid UUID, or the transcript contains no
                                          user/assistant messages.
                                      """
                                      if not _validate_uuid(session_id):
                                          return []
                                      if not agent_id:
                                          return []
                                      subagents_dir = _resolve_subagents_dir(session_id, directory)
                                      if subagents_dir is None:
                                          return []
                                      # The agent file may be directly in subagents/ or in a nested
                                      # subdirectory — scan to find it.
                                      match = next((p for id_, p in _collect_agent_files(subagents_dir) if id_ == agent_id), None)
                                      if match is None:
                                          return []
                                      try:
                                          content = match.read_text(encoding="utf-8")
                                      except OSError:
                                          return []
                                      if not content:
                                          return []
                                  
                                      # The .meta.json sidecar next to the transcript records which Agent
                                      # tool_use spawned this subagent (and, for nested subagents, the parent
                                      # agent id). A missing or unusable sidecar degrades to "no metadata".
                                      try:
                                          meta = _read_agent_metadata_sidecar(match)
                                      except OSError:
                                          meta = None
                                      parent_tool_use_id, parent_agent_id = _parent_ids_from_agent_metadata(meta)
                                  
                                      entries = _parse_transcript_entries(content)
                                      chain = _build_subagent_chain(entries)
                                      messages = [
                                          _to_session_message(e, parent_tool_use_id, parent_agent_id)
                                          for e in chain
                                          if e.get("type") in ("user", "assistant")
                                      ]
                                      if limit is not None and limit > 0:
                                          return messages[offset : offset + limit]
                                      if offset > 0:
                                          return messages[offset:]
                                      return messages
                                  

                                  list_sessions

                                  list_sessions(
                                      directory: str | None = None,
                                      limit: int | None = None,
                                      offset: int = 0,
                                      include_worktrees: bool = True,
                                  ) -> list[SDKSessionInfo]
                                  

                                  Lists sessions with metadata extracted from stat + head/tail reads.

                                  When directory is provided, returns sessions for that project directory and its git worktrees. When omitted, returns sessions across all projects.

                                  Use limit and offset for pagination.

                                  Parameters:

                                  Name Type Description Default
                                  directory str | None

                                  Directory to list sessions for. When provided, returns sessions for this project directory (and optionally its git worktrees). When omitted, returns sessions across all projects.

                                  None
                                  limit int | None

                                  Maximum number of sessions to return.

                                  None
                                  offset int

                                  Number of sessions to skip from the start of the sorted result set. Use with limit for pagination. Defaults to 0.

                                  0
                                  include_worktrees bool

                                  When directory is provided and the directory is inside a git repository, include sessions from all git worktree paths. Defaults to True.

                                  True

                                  Returns:

                                  Type Description
                                  list[SDKSessionInfo]

                                  List of SDKSessionInfo sorted by last_modified descending.

                                  Source code in src/clawd_code_sdk/_internal/sessions.py
                                  def list_sessions(
                                      directory: str | None = None,
                                      limit: int | None = None,
                                      offset: int = 0,
                                      include_worktrees: bool = True,
                                  ) -> list[SDKSessionInfo]:
                                      """Lists sessions with metadata extracted from stat + head/tail reads.
                                  
                                      When ``directory`` is provided, returns sessions for that project
                                      directory and its git worktrees. When omitted, returns sessions
                                      across all projects.
                                  
                                      Use ``limit`` and ``offset`` for pagination.
                                  
                                      Args:
                                          directory: Directory to list sessions for. When provided, returns
                                              sessions for this project directory (and optionally its git
                                              worktrees). When omitted, returns sessions across all projects.
                                          limit: Maximum number of sessions to return.
                                          offset: Number of sessions to skip from the start of the sorted
                                              result set. Use with ``limit`` for pagination. Defaults to 0.
                                          include_worktrees: When ``directory`` is provided and the directory
                                              is inside a git repository, include sessions from all git
                                              worktree paths. Defaults to ``True``.
                                  
                                      Returns:
                                          List of ``SDKSessionInfo`` sorted by ``last_modified`` descending.
                                      """
                                      if directory:
                                          return _list_sessions_for_project(directory, limit, offset, include_worktrees)
                                      return _list_all_sessions(limit, offset)
                                  

                                  list_subagents

                                  list_subagents(session_id: str, directory: str | None = None) -> list[str]
                                  

                                  Lists subagent IDs for a given session by scanning the subagents directory.

                                  Subagent transcripts are stored at ~/.claude/projects/<project>/<sessionId>/subagents/agent-<agentId>.jsonl (and may be nested in subdirectories such as workflows/<runId>/).

                                  Parameters:

                                  Name Type Description Default
                                  session_id str

                                  UUID of the parent session.

                                  required
                                  directory str | None

                                  Project directory to find the session in. If omitted, searches all project directories under ~/.claude/projects/.

                                  None

                                  Returns:

                                  Type Description
                                  list[str]

                                  List of subagent ID strings. Returns an empty list if the session

                                  list[str]

                                  is not found, the session_id is not a valid UUID, or the session

                                  list[str]

                                  has no subagents.

                                  Example

                                  List subagent IDs for a session::

                                  agent_ids = list_subagents(
                                      "550e8400-e29b-41d4-a716-446655440000",
                                      directory="/path/to/project",
                                  )
                                  
                                  Source code in src/clawd_code_sdk/_internal/sessions.py
                                  def list_subagents(session_id: str, directory: str | None = None) -> list[str]:
                                      """Lists subagent IDs for a given session by scanning the subagents directory.
                                  
                                      Subagent transcripts are stored at
                                      ``~/.claude/projects/<project>/<sessionId>/subagents/agent-<agentId>.jsonl``
                                      (and may be nested in subdirectories such as ``workflows/<runId>/``).
                                  
                                      Args:
                                          session_id: UUID of the parent session.
                                          directory: Project directory to find the session in. If omitted,
                                              searches all project directories under ``~/.claude/projects/``.
                                  
                                      Returns:
                                          List of subagent ID strings. Returns an empty list if the session
                                          is not found, the session_id is not a valid UUID, or the session
                                          has no subagents.
                                  
                                      Example:
                                          List subagent IDs for a session::
                                  
                                              agent_ids = list_subagents(
                                                  "550e8400-e29b-41d4-a716-446655440000",
                                                  directory="/path/to/project",
                                              )
                                      """
                                      if not _validate_uuid(session_id):
                                          return []
                                  
                                      subagents_dir = _resolve_subagents_dir(session_id, directory)
                                      if subagents_dir is None:
                                          return []
                                  
                                      return [agent_id for agent_id, _ in _collect_agent_files(subagents_dir)]
                                  

                                  rename_session

                                  rename_session(session_id: str, title: str, directory: str | None = None) -> None
                                  

                                  Rename a session by appending a custom-title entry.

                                  list_sessions reads the LAST custom-title from the file tail, so repeated calls are safe — the most recent wins.

                                  Parameters:

                                  Name Type Description Default
                                  session_id str

                                  UUID of the session to rename.

                                  required
                                  title str

                                  New session title. Leading/trailing whitespace is stripped. Must be non-empty after stripping.

                                  required
                                  directory str | None

                                  Project directory path (same semantics as list_sessions(directory=...)). When omitted, all project directories are searched for the session file.

                                  None

                                  Raises:

                                  Type Description
                                  ValueError

                                  If session_id is not a valid UUID, or if title is empty/whitespace-only.

                                  FileNotFoundError

                                  If the session file cannot be found.

                                  Example

                                  Rename a session in a specific project::

                                  rename_session(
                                      "550e8400-e29b-41d4-a716-446655440000",
                                      "My refactoring session",
                                      directory="/path/to/project",
                                  )
                                  
                                  Source code in src/clawd_code_sdk/_internal/session_mutations.py
                                  def rename_session(session_id: str, title: str, directory: str | None = None) -> None:
                                      """Rename a session by appending a custom-title entry.
                                  
                                      ``list_sessions`` reads the LAST custom-title from the file tail, so
                                      repeated calls are safe — the most recent wins.
                                  
                                      Args:
                                          session_id: UUID of the session to rename.
                                          title: New session title. Leading/trailing whitespace is stripped.
                                              Must be non-empty after stripping.
                                          directory: Project directory path (same semantics as
                                              ``list_sessions(directory=...)``). When omitted, all project
                                              directories are searched for the session file.
                                  
                                      Raises:
                                          ValueError: If ``session_id`` is not a valid UUID, or if ``title``
                                              is empty/whitespace-only.
                                          FileNotFoundError: If the session file cannot be found.
                                  
                                      Example:
                                          Rename a session in a specific project::
                                  
                                              rename_session(
                                                  "550e8400-e29b-41d4-a716-446655440000",
                                                  "My refactoring session",
                                                  directory="/path/to/project",
                                              )
                                      """
                                      if not _validate_uuid(session_id):
                                          raise ValueError(f"Invalid session_id: {session_id}")
                                      # Matches CLI guard — empty/whitespace titles are rejected rather than
                                      # overloaded as "clear title".
                                      stripped = title.strip()
                                      if not stripped:
                                          raise ValueError("title must be non-empty")
                                  
                                      data = (
                                          json.dumps(
                                              {
                                                  "type": "custom-title",
                                                  "customTitle": stripped,
                                                  "sessionId": session_id,
                                              },
                                              separators=(",", ":"),
                                          )
                                          + "\n"
                                      )
                                  
                                      _append_to_session(session_id, data, directory)
                                  

                                  tag_session

                                  tag_session(session_id: str, tag: str | None, directory: str | None = None) -> None
                                  

                                  Tag a session. Pass None to clear the tag.

                                  Appends a {type:'tag',tag:<tag>,sessionId:<id>} JSONL entry. list_sessions reads the LAST tag from the file tail — most recent wins. Passing None appends an empty-string tag entry which list_sessions treats as None (cleared).

                                  Tags are Unicode-sanitized before storing (removes zero-width chars, directional marks, private-use characters, etc.) for CLI filter compatibility.

                                  Parameters:

                                  Name Type Description Default
                                  session_id str

                                  UUID of the session to tag.

                                  required
                                  tag str | None

                                  Tag string, or None to clear. Leading/trailing whitespace is stripped. Must be non-empty after sanitization and stripping (unless None).

                                  required
                                  directory str | None

                                  Project directory path (same semantics as list_sessions(directory=...)). When omitted, all project directories are searched for the session file.

                                  None

                                  Raises:

                                  Type Description
                                  ValueError

                                  If session_id is not a valid UUID, or if tag is empty/whitespace-only after sanitization.

                                  FileNotFoundError

                                  If the session file cannot be found.

                                  Example

                                  Tag a session::

                                  tag_session(
                                      "550e8400-e29b-41d4-a716-446655440000",
                                      "experiment",
                                      directory="/path/to/project",
                                  )
                                  

                                  Clear a tag::

                                  tag_session(session_id, None)
                                  
                                  Source code in src/clawd_code_sdk/_internal/session_mutations.py
                                  def tag_session(
                                      session_id: str,
                                      tag: str | None,
                                      directory: str | None = None,
                                  ) -> None:
                                      """Tag a session. Pass ``None`` to clear the tag.
                                  
                                      Appends a ``{type:'tag',tag:<tag>,sessionId:<id>}`` JSONL entry.
                                      ``list_sessions`` reads the LAST tag from the file tail — most recent
                                      wins. Passing ``None`` appends an empty-string tag entry which
                                      ``list_sessions`` treats as ``None`` (cleared).
                                  
                                      Tags are Unicode-sanitized before storing (removes zero-width chars,
                                      directional marks, private-use characters, etc.) for CLI filter
                                      compatibility.
                                  
                                      Args:
                                          session_id: UUID of the session to tag.
                                          tag: Tag string, or ``None`` to clear. Leading/trailing whitespace
                                              is stripped. Must be non-empty after sanitization and stripping
                                              (unless ``None``).
                                          directory: Project directory path (same semantics as
                                              ``list_sessions(directory=...)``). When omitted, all project
                                              directories are searched for the session file.
                                  
                                      Raises:
                                          ValueError: If ``session_id`` is not a valid UUID, or if ``tag`` is
                                              empty/whitespace-only after sanitization.
                                          FileNotFoundError: If the session file cannot be found.
                                  
                                      Example:
                                          Tag a session::
                                  
                                              tag_session(
                                                  "550e8400-e29b-41d4-a716-446655440000",
                                                  "experiment",
                                                  directory="/path/to/project",
                                              )
                                  
                                          Clear a tag::
                                  
                                              tag_session(session_id, None)
                                      """
                                      if not _validate_uuid(session_id):
                                          raise ValueError(f"Invalid session_id: {session_id}")
                                      if tag is not None:
                                          sanitized = _sanitize_unicode(tag).strip()
                                          if not sanitized:
                                              raise ValueError("tag must be non-empty (use None to clear)")
                                          tag = sanitized
                                  
                                      data = (
                                          json.dumps(
                                              {
                                                  "type": "tag",
                                                  "tag": tag if tag is not None else "",
                                                  "sessionId": session_id,
                                              },
                                              separators=(",", ":"),
                                          )
                                          + "\n"
                                      )
                                  
                                      _append_to_session(session_id, data, directory)
                                  

                                  tool

                                  tool(
                                      name: str,
                                      description: str,
                                      input_schema: type | dict[str, Any],
                                      *,
                                      title: str | None = None,
                                      annotations: ToolAnnotations | None = None,
                                      output_schema: dict[str, Any] | None = None,
                                      meta: dict[str, Any] | None = None,
                                      search_hint: str | None = None,
                                      always_load: bool | None = None,
                                      max_result_size_chars: int | None = None,
                                  ) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]
                                  

                                  Decorator for defining MCP tools with type safety.

                                  Creates a tool that can be used with SDK MCP servers. The tool runs in-process within your Python application, providing better performance than external MCP servers.

                                  Parameters:

                                  Name Type Description Default
                                  name str

                                  Unique identifier for the tool. This is what Claude will use to reference the tool in function calls.

                                  required
                                  description str

                                  Human-readable description of what the tool does. This helps Claude understand when to use the tool.

                                  required
                                  input_schema type | dict[str, Any]

                                  Schema defining the tool's input parameters. Can be either: - A dictionary mapping parameter names to types (e.g., {"text": str}) - A TypedDict class for more complex schemas - A JSON Schema dictionary for full validation

                                  required
                                  title str | None

                                  Optional human-readable display name for the tool. If not set, clients typically use the name.

                                  None
                                  annotations ToolAnnotations | None

                                  Optional annotations for the tool.

                                  None
                                  output_schema dict[str, Any] | None

                                  Optional JSON Schema describing the tool's output format.

                                  None
                                  meta dict[str, Any] | None

                                  Optional metadata dict sent as _meta on the tool definition.

                                  None
                                  search_hint str | None

                                  Optional hint text for tool search/discovery.

                                  None
                                  always_load bool | None

                                  Optional flag indicating whether the tool should always be loaded.

                                  None
                                  max_result_size_chars int | None

                                  Optional size (in characters) up to which Claude Code keeps the tool's result inline instead of persisting it with a preview.

                                  None

                                  Returns:

                                  Type Description
                                  Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]

                                  A decorator function that wraps the tool implementation and returns

                                  Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]

                                  an SdkMcpTool instance ready for use with create_sdk_mcp_server().

                                  Notes
                                  • The tool function must be async
                                  • The function receives a single dict argument with the input parameters
                                  • The function should return a dict with a "content" key containing the response
                                  • Errors can be indicated by including "is_error": True in the response
                                  Source code in src/clawd_code_sdk/mcp_utils.py
                                  def tool(
                                      name: str,
                                      description: str,
                                      input_schema: type | dict[str, Any],
                                      *,
                                      title: str | None = None,
                                      annotations: ToolAnnotations | None = None,
                                      output_schema: dict[str, Any] | None = None,
                                      meta: dict[str, Any] | None = None,
                                      search_hint: str | None = None,
                                      always_load: bool | None = None,
                                      max_result_size_chars: int | None = None,
                                  ) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]:
                                      """Decorator for defining MCP tools with type safety.
                                  
                                      Creates a tool that can be used with SDK MCP servers. The tool runs
                                      in-process within your Python application, providing better performance
                                      than external MCP servers.
                                  
                                      Args:
                                          name: Unique identifier for the tool. This is what Claude will use
                                              to reference the tool in function calls.
                                          description: Human-readable description of what the tool does.
                                              This helps Claude understand when to use the tool.
                                          input_schema: Schema defining the tool's input parameters.
                                              Can be either:
                                              - A dictionary mapping parameter names to types (e.g., {"text": str})
                                              - A TypedDict class for more complex schemas
                                              - A JSON Schema dictionary for full validation
                                          title: Optional human-readable display name for the tool.
                                              If not set, clients typically use the name.
                                          annotations: Optional annotations for the tool.
                                          output_schema: Optional JSON Schema describing the tool's output format.
                                          meta: Optional metadata dict sent as ``_meta`` on the tool definition.
                                          search_hint: Optional hint text for tool search/discovery.
                                          always_load: Optional flag indicating whether the tool should always be loaded.
                                          max_result_size_chars: Optional size (in characters) up to which Claude Code
                                              keeps the tool's result inline instead of persisting it with a preview.
                                  
                                      Returns:
                                          A decorator function that wraps the tool implementation and returns
                                          an SdkMcpTool instance ready for use with create_sdk_mcp_server().
                                  
                                      Notes:
                                          - The tool function must be async
                                          - The function receives a single dict argument with the input parameters
                                          - The function should return a dict with a "content" key containing the response
                                          - Errors can be indicated by including "is_error": True in the response
                                      """
                                  
                                      def decorator(handler: Callable[[Any], Awaitable[dict[str, Any]]]) -> SdkMcpTool[Any]:
                                          return SdkMcpTool(
                                              name=name,
                                              description=description,
                                              input_schema=input_schema,
                                              handler=handler,
                                              title=title,
                                              annotations=annotations,
                                              output_schema=output_schema,
                                              meta=meta,
                                              search_hint=search_hint,
                                              always_load=always_load,
                                              max_result_size_chars=max_result_size_chars,
                                          )
                                  
                                      return decorator