Skip to content

models

Class info

Re-exported classes

Class Module Description
APIRetrySystemMessage clawd_code_sdk.models.system_messages System message emitted when an API call fails and is retried.
AgentAsyncLaunchedOutput clawd_code_sdk.models.output_types Output from the Task tool when an agent was launched asynchronously.
AgentCacheCreation clawd_code_sdk.models.output_types Cache creation token statistics.
AgentCompletedOutput clawd_code_sdk.models.output_types Output from the Task tool when the agent completed successfully.
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.
AgentInfo clawd_code_sdk.models.agents Information about an available subagent that can be invoked via the Agent tool.
AgentInput clawd_code_sdk.models.input_types Input for the Task tool. Launches a new agent to handle complex, multi-step tasks.
AgentOutputTextContent clawd_code_sdk.models.output_types A text content block in agent output.
AgentOutputUsage clawd_code_sdk.models.output_types Token usage statistics from an agent task.
AgentServerToolUse clawd_code_sdk.models.usage Server-side tool usage statistics.
AgentWireDefinition clawd_code_sdk.models.agents Wire-format agent definition matching the CLI control protocol.
ApiErrorParams clawd_code_sdk.models.messages Parameters of an API error, present only for the error kinds that have any (undocumented).
AppliedSettings clawd_code_sdk.models.control The currently applied model and effort settings.
AskUserQuestion clawd_code_sdk.models.input_types A single question to ask the user.
AskUserQuestionInput clawd_code_sdk.models.input_types Input for the AskUserQuestion tool.
AskUserQuestionItem clawd_code_sdk.models.output_types A single question that was asked.
AskUserQuestionOption clawd_code_sdk.models.input_types A single option for a user question.
AskUserQuestionOutput clawd_code_sdk.models.output_types tool_use_result for the AskUserQuestion tool.
AssistantMessage clawd_code_sdk.models.messages Assistant message with content blocks.
AssistantMessageContent clawd_code_sdk.models.content_blocks Assistant message payload mirroring anthropic.types.beta.BetaMessage.
AsyncHookJSONOutput clawd_code_sdk.models.hooks Async hook output that defers hook execution.
AuthStatusMessage clawd_code_sdk.models.messages Authentication status update.
BackgroundTasksChangedMessage clawd_code_sdk.models.system_messages Full snapshot of running background tasks, emitted whenever the set changes.
Base64PDFSource clawd_code_sdk.models.content_blocks Base64-encoded PDF document.
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.
BaseSessionConfig clawd_code_sdk.models.options Common fields for all session configurations.
BaseSystemMessage clawd_code_sdk.models.system_messages Base class for all system messages.
BashInput clawd_code_sdk.models.input_types Input for the Bash tool. Executes bash commands in a persistent shell session.
BashOutput clawd_code_sdk.models.output_types tool_use_result for the Bash tool.
BashOutputInput clawd_code_sdk.models.input_types Input for the BashOutput tool. Retrieves output from a background bash shell.
BashOutputOutput clawd_code_sdk.models.output_types tool_use_result for the BashOutput tool (background shell output retrieval).
ClaudeAgentOptions clawd_code_sdk.models.options Query options for Claude SDK.
ClaudeCodeAgentInfo clawd_code_sdk.models.server_info Information about an available subagent from Claude Code server.
ClaudeCodeCommandInfo clawd_code_sdk.models.server_info Information about an available slash command from Claude Code.
ClaudeCodeModelInfo clawd_code_sdk.models.server_info Information about an available AI model from Claude Code.
ClaudeCodeServerInfo clawd_code_sdk.models.server_info Complete server initialization info from Claude Code.
ClaudeCodeSettings clawd_code_sdk.models.settings Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings.
ClaudeOAuthWaitForCompletionResponse clawd_code_sdk.models.control Response from waiting for a Claude OAuth flow to complete.
CommandHookHandler clawd_code_sdk.models.hooks
CommandLifecycleMessage clawd_code_sdk.models.messages Progress of a user message that was sent with a uuid (capability msg_lifecycle_v1).
CommandsChangedMessage clawd_code_sdk.models.system_messages Emitted when the set of available slash commands changes.
CompactBoundarySystemMessage clawd_code_sdk.models.system_messages System message emitted at compaction boundaries.
ConfigOutput clawd_code_sdk.models.output_types Output from the Config tool.
ContentDocumentSource clawd_code_sdk.models.content_blocks Document made of content blocks (text / images).
ContextUsageAgent clawd_code_sdk.models.context_usage An agent contributing to context usage.
ContextUsageAttachmentBreakdown clawd_code_sdk.models.context_usage Token breakdown for a specific attachment type.
ContextUsageCategory clawd_code_sdk.models.context_usage A single category in the context usage breakdown.
ContextUsageDeferredBuiltinTool clawd_code_sdk.models.context_usage A deferred builtin tool contributing to context usage.
ContextUsageGridCell clawd_code_sdk.models.context_usage A single cell in the context usage grid visualization.
ContextUsageMcpInstructions clawd_code_sdk.models.context_usage MCP server instructions contributing to context usage.
ContextUsageMcpTool clawd_code_sdk.models.context_usage An MCP tool contributing to context usage.
ContextUsageMemoryFile clawd_code_sdk.models.context_usage A memory file contributing to context usage.
ContextUsageMessageBreakdown clawd_code_sdk.models.context_usage Breakdown of message tokens by category.
ContextUsageSkillFrontmatter clawd_code_sdk.models.context_usage A single skill's frontmatter contributing to context usage.
ContextUsageSkills clawd_code_sdk.models.context_usage Skills context usage summary.
ContextUsageSlashCommands clawd_code_sdk.models.context_usage Slash commands context usage summary.
ContextUsageSystemPromptSection clawd_code_sdk.models.context_usage A system prompt section contributing to context usage.
ContextUsageSystemTool clawd_code_sdk.models.context_usage A system tool contributing to context usage.
ContextUsageToolCallBreakdown clawd_code_sdk.models.context_usage Token breakdown for a specific tool call type.
ContinueLatest clawd_code_sdk.models.options Continue the most recent conversation.
ControlErrorResponse clawd_code_sdk.models.control Control Error response.
ControlRequestProgressMessage clawd_code_sdk.models.system_messages Progress for a long-running control request (e.g. side question).
ControlResponse clawd_code_sdk.models.control Control response.
ConversationResetMessage clawd_code_sdk.models.messages Emitted when the CLI starts a new conversation within the same session.
CwdChangedHookInput clawd_code_sdk.models.hooks Input data for CwdChanged hook events.
CwdChangedHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for CwdChanged events.
DirectoryAddedHookInput clawd_code_sdk.models.hooks Input data for DirectoryAdded hook events.
DocumentBlock clawd_code_sdk.models.content_blocks Document content block (e.g. an attached PDF) in a user message.
EditOutput clawd_code_sdk.models.output_types tool_use_result for the Edit tool.
ElicitationCompleteMessage clawd_code_sdk.models.system_messages System message emitted when an MCP elicitation completes.
ElicitationHookInput clawd_code_sdk.models.hooks Input data for Elicitation hook events.
ElicitationHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for Elicitation events.
ElicitationResultHookInput clawd_code_sdk.models.hooks Input data for ElicitationResult hook events.
ElicitationResultHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for ElicitationResult events.
EnterPlanModeInput clawd_code_sdk.models.input_types Input for the EnterPlanMode tool. Enters planning mode.
EnterPlanModeOutput clawd_code_sdk.models.output_types tool_use_result for the EnterPlanMode tool.
EnterWorktreeOutput clawd_code_sdk.models.output_types tool_use_result for the EnterWorktree tool.
ExitPlanModeInput clawd_code_sdk.models.input_types Input for the ExitPlanMode tool. Exits planning mode for user approval.
ExitPlanModeOutput clawd_code_sdk.models.output_types tool_use_result for the ExitPlanMode tool.
ExitWorktreeInput clawd_code_sdk.models.input_types Input for the ExitWorktree tool.
ExitWorktreeOutput clawd_code_sdk.models.output_types tool_use_result for the ExitWorktree tool.
FileChangedHookInput clawd_code_sdk.models.hooks Input data for FileChanged hook events.
FileChangedHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for FileChanged events.
FileDocumentSource clawd_code_sdk.models.content_blocks Document uploaded through the Files API.
FileEditInput clawd_code_sdk.models.input_types Input for the Edit tool. Performs exact string replacements in files.
FileReadInput clawd_code_sdk.models.input_types Input for the Read tool. Reads files including text, images, PDFs, and notebooks.
FileWriteInput clawd_code_sdk.models.input_types Input for the Write tool. Writes a file to the local filesystem.
FilesPersistedSystemMessage clawd_code_sdk.models.system_messages System message emitted when files have been persisted.
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.
GitDiff clawd_code_sdk.models.output_types Git diff information for a file change.
GlobInput clawd_code_sdk.models.input_types Input for the Glob tool. Fast file pattern matching.
GlobOutput clawd_code_sdk.models.output_types tool_use_result for the Glob tool.
GrepInput clawd_code_sdk.models.input_types
GrepOutput clawd_code_sdk.models.output_types tool_use_result for the Grep tool (all modes).
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.
HookProgressSystemMessage clawd_code_sdk.models.system_messages Progress update from a running hook.
HookResponseSystemMessage clawd_code_sdk.models.system_messages System message emitted when a hook completes.
HookStartedSystemMessage clawd_code_sdk.models.system_messages System message emitted when a hook starts.
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.
InformationalSystemMessage clawd_code_sdk.models.system_messages Informational text from the CLI (notices, suggestions, warnings).
InitSystemMessage clawd_code_sdk.models.system_messages System init message with session metadata.
InstructionsLoadedHookInput clawd_code_sdk.models.hooks Input data for InstructionsLoaded hook events.
JSONRPCError clawd_code_sdk.models.mcp A JSON-RPC error object.
JSONRPCErrorResponse clawd_code_sdk.models.mcp A response to a request that indicates an error occurred.
JSONRPCNotification clawd_code_sdk.models.mcp A JSON-RPC notification which does not expect a response.
JSONRPCRequest clawd_code_sdk.models.mcp A JSON-RPC request that expects a response.
JSONRPCResultResponse clawd_code_sdk.models.mcp A successful (non-error) response to a request.
KillShellInput clawd_code_sdk.models.input_types Input for the KillBash tool. Kills a running background bash shell.
KillShellOutput clawd_code_sdk.models.output_types tool_use_result for the KillBash tool.
ListMcpResourcesInput clawd_code_sdk.models.input_types Input for the ListMcpResources tool. Lists available MCP resources.
LocalCommandOutputMessage clawd_code_sdk.models.system_messages Output from a local slash command (e.g. /voice, /cost).
McpAuthenticateResponse clawd_code_sdk.models.control Response from authenticating with an MCP server.
McpClaudeAIProxyServerConfig clawd_code_sdk.models.mcp MCP Claude AI proxy server configuration.
McpHttpServerConfig clawd_code_sdk.models.mcp MCP HTTP server configuration.
McpResourceContents clawd_code_sdk.models.control A single resource content entry.
McpResourceEntry clawd_code_sdk.models.output_types A single MCP resource entry.
McpSSEServerConfig clawd_code_sdk.models.mcp MCP SSE server configuration.
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.
McpServerProvenance clawd_code_sdk.models.hooks Which MCP server (and config source) a tool call belongs to.
McpServerStatus clawd_code_sdk.models.system_messages MCP server status.
McpServerStatusEntry clawd_code_sdk.models.mcp Status information for a single MCP server.
McpServerVersionInfo clawd_code_sdk.models.mcp Server version information returned in MCP status.
McpSetServersResult clawd_code_sdk.models.mcp Result of a setMcpServers operation.
McpStatusResponse clawd_code_sdk.models.mcp Response from get_mcp_status() containing all MCP server statuses.
McpStdioServerConfig clawd_code_sdk.models.mcp MCP stdio server configuration.
McpToolStatus clawd_code_sdk.models.mcp Status information for a single MCP tool.
MemoryRecallSystemMessage clawd_code_sdk.models.system_messages Emitted when the memory recall supervisor surfaces relevant memories into the turn.
MessageDisplayHookInput clawd_code_sdk.models.hooks Input data for MessageDisplay hook events (assistant text being displayed).
MessageDisplayHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for MessageDisplay events.
MessageParam clawd_code_sdk.models.content_blocks User message payload wrapping content blocks.
MirrorErrorSystemMessage clawd_code_sdk.models.system_messages Emitted when SessionStore.append() rejects or times out for a transcript-mirror batch.
ModelRefusalFallbackMessage clawd_code_sdk.models.system_messages Emitted when a model refusal triggered a switch to a fallback model.
ModelRefusalNoFallbackMessage clawd_code_sdk.models.system_messages Emitted when the model refused and no fallback model is available.
ModelScopedUsageWindow clawd_code_sdk.models.context_usage Per-model weekly window.
ModelUsage clawd_code_sdk.models.usage Cumulative token usage per model, accumulated across the entire session.
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.
NotebookEditInput clawd_code_sdk.models.input_types Input for the NotebookEdit tool. Edits cells in Jupyter notebook files.
NotebookEditOutput clawd_code_sdk.models.output_types tool_use_result for the NotebookEdit tool.
NotificationHookInput clawd_code_sdk.models.hooks Input data for Notification hook events.
NotificationHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for Notification events.
NotificationSystemMessage clawd_code_sdk.models.system_messages Loop-side text notification.
PermissionDeniedHookInput clawd_code_sdk.models.hooks Input data for PermissionDenied hook events.
PermissionDeniedHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for PermissionDenied events.
PermissionDeniedSystemMessage clawd_code_sdk.models.system_messages Emitted when a tool call was denied by the permission system.
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.
PermissionRuleValue clawd_code_sdk.models.permissions Permission rule value.
Permissions clawd_code_sdk.models.settings Tool usage permissions configuration.
PlainTextSource clawd_code_sdk.models.content_blocks Plain text document.
PluginInstallSystemMessage clawd_code_sdk.models.system_messages System message emitted when a plugin is installed.
PostCompactHookInput clawd_code_sdk.models.hooks Input data for PostCompact hook events.
PostModelSwitchHookInput clawd_code_sdk.models.hooks Input data for PostModelSwitch hook events (after the session model changed).
PostModelSwitchHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for PostModelSwitch 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.
PostToolUseHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for PostToolUse events.
PreCompactHookInput clawd_code_sdk.models.hooks Input data for PreCompact hook events.
PreModelSwitchHookInput clawd_code_sdk.models.hooks Input data for PreModelSwitch hook events (before the session model changes).
PreModelSwitchHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for PreModelSwitch events.
PreSkillShellCommandHookInput clawd_code_sdk.models.hooks Input data for PreSkillShellCommand hook events.
PreSkillShellCommandHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for PreSkillShellCommand events (refuse or rewrite the command).
PreSkillShellCommandToolInput clawd_code_sdk.models.hooks Tool input of a PreSkillShellCommand hook.
PreToolUseHookInput clawd_code_sdk.models.hooks Input data for PreToolUse hook events.
PreToolUseHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for PreToolUse events.
PromptHookHandler clawd_code_sdk.models.hooks LLM prompt hook handler.
PromptRequest clawd_code_sdk.models.prompt_requests Prompt request sent to the SDK consumer.
PromptRequestOption clawd_code_sdk.models.prompt_requests An option in a prompt request.
PromptResponse clawd_code_sdk.models.prompt_requests Response to a prompt request.
PromptSuggestionMessage clawd_code_sdk.models.messages Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.
RateLimitInfo clawd_code_sdk.models.messages Rate limit information.
RateLimitMessage clawd_code_sdk.models.messages Rate limit event message.
ReadFileInfo clawd_code_sdk.models.output_types Nested file info inside a Read tool result (text mode).
ReadImageDimensions clawd_code_sdk.models.output_types Image dimension info for coordinate mapping.
ReadImageFileInfo clawd_code_sdk.models.output_types Nested file info for image reads.
ReadImageOutput clawd_code_sdk.models.output_types tool_use_result for the Read tool (image files).
ReadMcpResourceContentItem clawd_code_sdk.models.output_types A single content item from an MCP resource.
ReadMcpResourceInput clawd_code_sdk.models.input_types Input for the ReadMcpResource tool. Reads a specific MCP resource from a server.
ReadMcpResourceOutput clawd_code_sdk.models.output_types tool_use_result for the ReadMcpResource tool.
ReadNotebookFileInfo clawd_code_sdk.models.output_types Nested file info for notebook reads.
ReadNotebookOutput clawd_code_sdk.models.output_types tool_use_result for the Read tool (Jupyter notebooks).
ReadPartsFileInfo clawd_code_sdk.models.output_types Nested file info for PDF parts (extracted page images).
ReadPartsOutput clawd_code_sdk.models.output_types tool_use_result for the Read tool (PDF parts extraction).
ReadPdfFileInfo clawd_code_sdk.models.output_types Nested file info for PDF reads.
ReadPdfOutput clawd_code_sdk.models.output_types tool_use_result for the Read tool (PDF files).
ReadTextOutput clawd_code_sdk.models.output_types tool_use_result for the Read tool (text files).
ReloadPluginsCacheImpact clawd_code_sdk.models.control How a reload would change the session's tool list.
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.
SDKContextUsage clawd_code_sdk.models.context_usage Compact context usage snapshot, attached to assistant messages.
SDKControlApplyFlagSettingsRequest clawd_code_sdk.models.control SDK control apply flag settings request.
SDKControlBackgroundTasksRequest clawd_code_sdk.models.control Moves running foreground tasks (or one tool use) to the background.
SDKControlCancelAsyncMessageRequest clawd_code_sdk.models.control Drops a pending async user message from the command queue by uuid.
SDKControlChannelEnableRequest clawd_code_sdk.models.control Enables MCP channel notifications for a marketplace plugin server.
SDKControlClaudeOAuthWaitForCompletionRequest clawd_code_sdk.models.control Waits for an in-progress Claude OAuth flow to complete.
SDKControlElicitationRequest clawd_code_sdk.models.control Requests the SDK consumer to handle an MCP elicitation (user input request).
SDKControlEndSessionRequest clawd_code_sdk.models.control Ends the current session.
SDKControlFileSuggestionsRequest clawd_code_sdk.models.control Requests at-mention file autocomplete suggestions for a partial path prefix.
SDKControlGenerateSessionTitleRequest clawd_code_sdk.models.control Generates a title for a session from a description of it.
SDKControlGetBinaryVersionRequest clawd_code_sdk.models.control Requests the version of the running Claude Code binary.
SDKControlGetContextUsageRequest clawd_code_sdk.models.control Requests a breakdown of current context window usage by category.
SDKControlGetContextUsageResponse clawd_code_sdk.models.context_usage Breakdown of current context window usage by category.
SDKControlGetHooksListingRequest clawd_code_sdk.models.control Requests the listing of configured hooks (same data as /hooks).
SDKControlGetSettingsRequest clawd_code_sdk.models.control Returns the effective merged settings and the raw per-source settings.
SDKControlGetTaskOutputRequest clawd_code_sdk.models.control Reads the output collected so far for a background task.
SDKControlGetTaskOutputResponse clawd_code_sdk.models.control Output of a background task.
SDKControlGetUsageRequest clawd_code_sdk.models.control Requests the structured usage report (session cost + rate limits). Experimental.
SDKControlGetUsageResponse clawd_code_sdk.models.control Structured /usage data: session totals and plan rate-limit windows. Experimental.
SDKControlInitializeRequest clawd_code_sdk.models.control SDK control initialize request.
SDKControlInterruptRequest clawd_code_sdk.models.control SDK control interrupt request.
SDKControlInterruptResponse clawd_code_sdk.models.control Response to an interrupt request.
SDKControlListModelsRequest clawd_code_sdk.models.control Requests the list of available models.
SDKControlListPermissionRulesRequest clawd_code_sdk.models.control Lists the effective permission rules.
SDKControlMcpAuthenticateRequest clawd_code_sdk.models.control Authenticates with an MCP server.
SDKControlMcpCallRequest clawd_code_sdk.models.control Invokes an MCP tool via the subprocess MCP client without a model turn.
SDKControlMcpClearAuthRequest clawd_code_sdk.models.control Clears authentication for an MCP server.
SDKControlMcpMessageRequest clawd_code_sdk.models.control SDK control MCP message request.
SDKControlMcpOAuthCallbackUrlRequest clawd_code_sdk.models.control Provides an OAuth redirect callback URL to complete an MCP server OAuth flow.
SDKControlMcpReadResourceRequest clawd_code_sdk.models.control Reads a resource from a connected MCP server.
SDKControlMcpReadResourceResponse clawd_code_sdk.models.control Contents of an MCP resource.
SDKControlMcpReconnectRequest clawd_code_sdk.models.control Reconnects a disconnected or failed MCP server.
SDKControlMcpSetServersRequest clawd_code_sdk.models.control Replaces the set of dynamically managed MCP servers.
SDKControlMcpStatusRequest clawd_code_sdk.models.control Requests the current status of all MCP server connections.
SDKControlMcpToggleRequest clawd_code_sdk.models.control Enables or disables an MCP server.
SDKControlPermissionRequest clawd_code_sdk.models.control SDK control permission request.
SDKControlReadFileRequest clawd_code_sdk.models.control Read a file from the session filesystem for the remote sidebar viewer.
SDKControlReadFileResponse clawd_code_sdk.models.control File contents for the remote sidebar viewer.
SDKControlRegisterRepoRootRequest clawd_code_sdk.models.control Registers an additional repository root (like /add-dir).
SDKControlReloadOutputStylesRequest clawd_code_sdk.models.control Re-scans output styles from disk.
SDKControlReloadOutputStylesResponse clawd_code_sdk.models.control Output styles after reload.
SDKControlReloadSkillsRequest clawd_code_sdk.models.control Re-scans skills from disk.
SDKControlReloadSkillsResponse clawd_code_sdk.models.control Skills after reload.
SDKControlRemoteControlRequest clawd_code_sdk.models.control Toggles the remote control REPL bridge for external session access.
SDKControlRequest clawd_code_sdk.models.control SDK control request.
SDKControlResponse clawd_code_sdk.models.control SDK Control response.
SDKControlRewindFilesRequest clawd_code_sdk.models.control SDK control rewind files request.
SDKControlSeedReadStateRequest clawd_code_sdk.models.control Seeds the readFileState cache with a path+mtime entry.
SDKControlSetHasSubscribersRequest clawd_code_sdk.models.control Tells the CLI whether anyone is watching the session output.
SDKControlSetMaxThinkingTokensRequest clawd_code_sdk.models.control Sets the maximum number of thinking tokens for extended thinking.
SDKControlSetModelRequest clawd_code_sdk.models.control Sets the model to use for subsequent conversation turns.
SDKControlSetPermissionModeRequest clawd_code_sdk.models.control SDK control set permission mode request.
SDKControlSetPermissionModeResponse clawd_code_sdk.models.control Response to a set_permission_mode request.
SDKControlSetProactiveRequest clawd_code_sdk.models.control Sets proactive mode configuration.
SDKControlSideQuestionRequest clawd_code_sdk.models.control Sends a side question to the model using the current conversation context.
SDKControlStopTaskRequest clawd_code_sdk.models.control SDK control stop task request.
SDKControlUpdateSettingsRequest clawd_code_sdk.models.control Writes settings to the local or user settings file.
SDKDeferredToolUse clawd_code_sdk.models.output_types A deferred tool use from a completed agent result.
SDKHookCallbackRequest clawd_code_sdk.models.control SDK hook callback request.
SDKPermissionDenial clawd_code_sdk.models.messages Permission denial from Claude API response.
SDKSessionInfo clawd_code_sdk.models.session Session metadata returned by list_sessions.
SDKUsageReport clawd_code_sdk.models.context_usage Session usage report (same data as /usage).
Sandbox clawd_code_sdk.models.settings Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing.
SdkPluginConfig clawd_code_sdk.models.mcp SDK plugin configuration.
SessionEndHookInput clawd_code_sdk.models.hooks Input data for SessionEnd hook events.
SessionKey clawd_code_sdk.models.system_messages Identifies a session transcript or subagent transcript in the store.
SessionMessage clawd_code_sdk.models.session A message from a session transcript.
SessionStartHookInput clawd_code_sdk.models.hooks Input data for SessionStart hook events.
SessionStartHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for SessionStart events.
SessionStateChangedMessage clawd_code_sdk.models.system_messages System message emitted when session state changes.
SessionWritesLostMessage clawd_code_sdk.models.system_messages Emitted when writes were lost due to a full disk or exceeded quota.
SettingsSource clawd_code_sdk.models.control A single settings source with its raw settings.
SetupHookInput clawd_code_sdk.models.hooks Input data for Setup hook events.
SideQuestionResponse clawd_code_sdk.models.control Response from a side question.
SkillInput clawd_code_sdk.models.input_types Input for the Skill tool. Invokes a named skill (slash command).
SkillOutput clawd_code_sdk.models.output_types tool_use_result for the Skill tool.
StatusSystemMessage clawd_code_sdk.models.system_messages System status message.
StopHookInput clawd_code_sdk.models.hooks Input data for Stop hook events.
StopHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for Stop events.
StreamEvent clawd_code_sdk.models.messages Stream event for partial message updates during streaming.
StructuredPatchHunk clawd_code_sdk.models.output_types A single hunk in a structured patch.
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.
SubagentStopHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for SubagentStop events.
SyncHookJSONOutput clawd_code_sdk.models.hooks Synchronous hook output with control and decision fields.
TaskCompletedHookInput clawd_code_sdk.models.hooks Input data for TaskCompleted hook events.
TaskCreatedHookInput clawd_code_sdk.models.hooks Input data for TaskCreated hook events.
TaskInfo clawd_code_sdk.models.output_types Information about a background task.
TaskNotificationSystemMessage clawd_code_sdk.models.system_messages System message emitted when a subagent task completes, fails, or stops.
TaskOutputResult clawd_code_sdk.models.output_types tool_use_result for the TaskOutput tool (background task polling).
TaskProgressSystemMessage clawd_code_sdk.models.system_messages System message emitted periodically with task progress updates.
TaskProgressUsage clawd_code_sdk.models.system_messages Usage info for a task progress update.
TaskStartedSystemMessage clawd_code_sdk.models.system_messages System message emitted when a subagent task starts.
TaskStopOutput clawd_code_sdk.models.output_types tool_use_result for the TaskStop tool.
TaskUpdatedSystemMessage clawd_code_sdk.models.system_messages System message emitted when a subagent task was updated.
TeammateIdleHookInput clawd_code_sdk.models.hooks Input data for TeammateIdle 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.
ThinkingTokensMessage clawd_code_sdk.models.system_messages Running estimate of thinking tokens for the current turn.
TodoItem clawd_code_sdk.models.input_types A single todo item.
TodoWriteInput clawd_code_sdk.models.input_types Input for the TodoWrite tool. Creates and manages a structured task list.
TodoWriteOutput clawd_code_sdk.models.output_types tool_use_result for the TodoWrite tool.
ToolConfig clawd_code_sdk.models.options Per-tool configuration for built-in tools.
ToolPermissionContext clawd_code_sdk.models.permissions Context information for tool permission callbacks.
ToolProgressMessage clawd_code_sdk.models.messages Progress update for a running tool.
ToolResultBlock clawd_code_sdk.models.content_blocks Tool result content block.
ToolUseBlock clawd_code_sdk.models.content_blocks Tool use content block.
ToolUseMeta clawd_code_sdk.models.messages Display metadata for a tool_use block in an assistant message (undocumented).
ToolUseSummaryMessage clawd_code_sdk.models.messages Summary of preceding tool uses.
ToolsPreset clawd_code_sdk.models.agents Tools preset configuration.
TriggerMetadata clawd_code_sdk.models.system_messages Trigger metadata.
URLPDFSource clawd_code_sdk.models.content_blocks PDF document referenced by URL.
Usage clawd_code_sdk.models.usage Token usage counters.
UsageMoney clawd_code_sdk.models.context_usage An amount in minor units (amount_minor / 10**exponent in currency).
UsageRateLimits clawd_code_sdk.models.context_usage Plan rate-limit windows from the claude.ai usage endpoint.
UsageSpend clawd_code_sdk.models.context_usage Usage-credit spend beyond the plan windows (undocumented, server-defined).
UsageWindow clawd_code_sdk.models.context_usage Utilization of one plan rate-limit window.
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.
UserFilePrompt clawd_code_sdk.models.prompts A user prompt referencing a file uploaded via the Anthropic Files API.
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.
UserPromptExpansionHookInput clawd_code_sdk.models.hooks Input data for UserPromptExpansion hook events.
UserPromptExpansionHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for UserPromptExpansion events.
UserPromptSubmitHookInput clawd_code_sdk.models.hooks Input data for UserPromptSubmit hook events.
UserPromptSubmitHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for UserPromptSubmit events.
UserTextPrompt clawd_code_sdk.models.prompts A text-only user prompt.
WebFetchInput clawd_code_sdk.models.input_types Input for the WebFetch tool. Fetches content from a URL and processes it with AI.
WebFetchOutput clawd_code_sdk.models.output_types tool_use_result for the WebFetch tool.
WebSearchHit clawd_code_sdk.models.output_types A single search result hit.
WebSearchInput clawd_code_sdk.models.input_types Input for the WebSearch tool. Searches the web and returns formatted results.
WebSearchOutput clawd_code_sdk.models.output_types tool_use_result for the WebSearch tool.
WebSearchToolResult clawd_code_sdk.models.output_types A structured search result entry.
WorkerShuttingDownMessage clawd_code_sdk.models.system_messages Emitted when the CLI worker is shutting down.
WorktreeCreateHookInput clawd_code_sdk.models.hooks Input data for WorktreeCreate hook events.
WorktreeCreateHookSpecificOutput clawd_code_sdk.models.hooks Hook-specific output for WorktreeCreate events.
WorktreeRemoveHookInput clawd_code_sdk.models.hooks Input data for WorktreeRemove hook events.
WriteOutput clawd_code_sdk.models.output_types tool_use_result for the Write tool.

🛈 DocStrings

Type definitions for Claude SDK.

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"}],
        }
    ],
}

AssistantContentBlock module-attribute

AssistantContentBlock = Annotated[
    TextBlock | ThinkingBlock | ToolUseBlock | ServerContentBlock, Discriminator("type")
]

Content blocks that appear in assistant messages (any Messages API block type).

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

CommandLifecycleState module-attribute

CommandLifecycleState = Literal[
    "queued", "started", "completed", "cancelled", "discarded", "refused"
]

Where a uuid-stamped user message is in the CLI's command queue.

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).

GrepInput module-attribute

GrepInput = TypedDict(
    "GrepInput",
    {
        "pattern": str,
        "path": NotRequired[str],
        "glob": NotRequired[str],
        "type": NotRequired[str],
        "output_mode": NotRequired[Literal["content", "files_with_matches", "count"]],
        "-i": NotRequired[bool],
        "-n": NotRequired[bool],
        "-o": NotRequired[bool],
        "-B": NotRequired[int],
        "-A": NotRequired[int],
        "-C": NotRequired[int],
        "head_limit": NotRequired[int],
        "multiline": NotRequired[bool],
    },
)

Input for the Grep tool. Powerful search built on ripgrep with regex support.

HookHandler module-attribute

Union of all declarative hook handler types.

ListMcpResourcesOutput module-attribute

ListMcpResourcesOutput = list[McpResourceEntry]

tool_use_result for the ListMcpResources tool.

McpOutput module-attribute

McpOutput = str | list[dict[str, Any]] | dict[str, Any]

Output from a generic MCP tool call (plain string).

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.

OnElicitation module-attribute

OnElicitation = Callable[[SDKControlElicitationRequest], Awaitable[ElicitResult]]

Callback for handling MCP elicitation requests.

Called when an MCP server requests user input and no hook handles it. If not provided, elicitation requests will be declined automatically.

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.

SERVER_CONTENT_BLOCK_TYPES module-attribute

SERVER_CONTENT_BLOCK_TYPES: tuple[type[BaseModel], ...] = get_args(ServerContentBlock.__value__)

Runtime tuple of :data:ServerContentBlock members (for isinstance checks).

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).

UserContentBlock module-attribute

UserContentBlock = Annotated[
    TextBlock | ToolResultBlock | ImageBlock | DocumentBlock, Discriminator("type")
]

Content blocks that appear in user messages.

UserPrompt module-attribute

Union type for all user prompt dataclasses.

ServerContentBlock

ServerContentBlock = (
    BetaRedactedThinkingBlock
    | BetaServerToolUseBlock
    | BetaWebSearchToolResultBlock
    | BetaWebFetchToolResultBlock
    | BetaAdvisorToolResultBlock
    | BetaCodeExecutionToolResultBlock
    | BetaBashCodeExecutionToolResultBlock
    | BetaTextEditorCodeExecutionToolResultBlock
    | BetaToolSearchToolResultBlock
    | BetaMCPToolUseBlock
    | BetaMCPToolResultBlock
    | BetaContainerUploadBlock
    | BetaCompactionBlock
    | BetaFallbackBlock
    | BetaMCPToolListingBlock
)

Assistant content blocks produced by the API itself (server tools, MCP connector, ...).

These use the Anthropic SDK's models directly; clawd has no extra behaviour for them.

APIRetrySystemMessage

Bases: BaseSystemMessage

System message emitted when an API call fails and is retried.

Source code in src/clawd_code_sdk/models/system_messages.py
class APIRetrySystemMessage(BaseSystemMessage):
    """System message emitted when an API call fails and is retried."""

    subtype: Literal["api_retry"] = "api_retry"
    attempt: int
    max_retries: int
    retry_delay_ms: float
    error_status: int | None
    error: AssistantMessageError
    no_response: NoResponseInfo | None = None
    """Set when the retry was triggered by the API not responding at all."""

no_response class-attribute instance-attribute

no_response: NoResponseInfo | None = None

Set when the retry was triggered by the API not responding at all.

AgentAsyncLaunchedOutput

Bases: TypedDict

Output from the Task tool when an agent was launched asynchronously.

Source code in src/clawd_code_sdk/models/output_types.py
class AgentAsyncLaunchedOutput(TypedDict):
    """Output from the Task tool when an agent was launched asynchronously."""

    status: Literal["async_launched"]
    """Indicates the agent was launched in the background."""
    isAsync: NotRequired[Literal[True]]
    """Always True for async-launched agents."""
    agentId: str
    """The ID of the async agent."""
    description: str
    """The description of the task."""
    resolvedModel: NotRequired[str]
    """Model in use at the backgrounding transition."""
    modelsUsed: NotRequired[list[str]]
    """Ordered distinct models used before backgrounding."""
    prompt: str
    """The prompt for the agent."""
    outputFile: str
    """Path to the output file for checking agent progress."""
    canReadOutputFile: NotRequired[bool]
    """Whether the calling agent has Read/Bash tools to check progress."""

agentId instance-attribute

agentId: str

The ID of the async agent.

canReadOutputFile instance-attribute

canReadOutputFile: NotRequired[bool]

Whether the calling agent has Read/Bash tools to check progress.

description instance-attribute

description: str

The description of the task.

isAsync instance-attribute

isAsync: NotRequired[Literal[True]]

Always True for async-launched agents.

modelsUsed instance-attribute

modelsUsed: NotRequired[list[str]]

Ordered distinct models used before backgrounding.

outputFile instance-attribute

outputFile: str

Path to the output file for checking agent progress.

prompt instance-attribute

prompt: str

The prompt for the agent.

resolvedModel instance-attribute

resolvedModel: NotRequired[str]

Model in use at the backgrounding transition.

status instance-attribute

status: Literal['async_launched']

Indicates the agent was launched in the background.

AgentCacheCreation

Bases: TypedDict

Cache creation token statistics.

Source code in src/clawd_code_sdk/models/output_types.py
class AgentCacheCreation(TypedDict):
    """Cache creation token statistics."""

    ephemeral_1h_input_tokens: int
    """Tokens for 1-hour ephemeral cache entries."""
    ephemeral_5m_input_tokens: int
    """Tokens for 5-minute ephemeral cache entries."""

ephemeral_1h_input_tokens instance-attribute

ephemeral_1h_input_tokens: int

Tokens for 1-hour ephemeral cache entries.

ephemeral_5m_input_tokens instance-attribute

ephemeral_5m_input_tokens: int

Tokens for 5-minute ephemeral cache entries.

AgentCompletedOutput

Bases: TypedDict

Output from the Task tool when the agent completed successfully.

Source code in src/clawd_code_sdk/models/output_types.py
class AgentCompletedOutput(TypedDict):
    """Output from the Task tool when the agent completed successfully."""

    status: Literal["completed"]
    """Agent completion status."""
    agentId: str
    """ID of the agent that ran."""
    agentType: NotRequired[str]
    """Type of the agent that ran."""
    content: list[AgentOutputTextContent]
    """Text content blocks produced by the agent."""
    resolvedModel: NotRequired[str]
    """Model the agent ran on."""
    modelsUsed: NotRequired[list[str]]
    """Ordered distinct models used (length > 1 means a mid-run swap)."""
    totalToolUseCount: int
    """Total number of tool calls made."""
    totalDurationMs: int
    """Total execution duration in milliseconds."""
    totalTokens: int
    """Total tokens used."""
    usage: AgentOutputUsage
    """Detailed token usage statistics."""
    toolsUsed: NotRequired[list[str]]
    """Names of the tools the agent used."""
    toolStats: NotRequired[ToolStats]
    """Tool usage statistics."""
    prompt: str
    """The prompt that was given to the agent."""
    worktreePath: NotRequired[str]
    """Worktree the agent ran in (isolation="worktree")."""
    worktreeBranch: NotRequired[str]
    """Branch of the agent's worktree."""

agentId instance-attribute

agentId: str

ID of the agent that ran.

agentType instance-attribute

agentType: NotRequired[str]

Type of the agent that ran.

content instance-attribute

content: list[AgentOutputTextContent]

Text content blocks produced by the agent.

modelsUsed instance-attribute

modelsUsed: NotRequired[list[str]]

Ordered distinct models used (length > 1 means a mid-run swap).

prompt instance-attribute

prompt: str

The prompt that was given to the agent.

resolvedModel instance-attribute

resolvedModel: NotRequired[str]

Model the agent ran on.

status instance-attribute

status: Literal['completed']

Agent completion status.

toolStats instance-attribute

toolStats: NotRequired[ToolStats]

Tool usage statistics.

toolsUsed instance-attribute

toolsUsed: NotRequired[list[str]]

Names of the tools the agent used.

totalDurationMs instance-attribute

totalDurationMs: int

Total execution duration in milliseconds.

totalTokens instance-attribute

totalTokens: int

Total tokens used.

totalToolUseCount instance-attribute

totalToolUseCount: int

Total number of tool calls made.

usage instance-attribute

Detailed token usage statistics.

worktreeBranch instance-attribute

worktreeBranch: NotRequired[str]

Branch of the agent's worktree.

worktreePath instance-attribute

worktreePath: NotRequired[str]

Worktree the agent ran in (isolation="worktree").

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]

AgentInfo

Bases: ClaudeCodeBaseModel

Information about an available subagent that can be invoked via the Agent tool.

Source code in src/clawd_code_sdk/models/agents.py
class AgentInfo(ClaudeCodeBaseModel):
    """Information about an available subagent that can be invoked via the Agent tool."""

    name: str
    """Agent type identifier (e.g., "Explore")."""

    description: str
    """Description of when to use this agent."""

    model: Model | str | None = None
    """Model alias this agent uses. If omitted, inherits the parent's model."""

description instance-attribute

description: str

Description of when to use this agent.

model class-attribute instance-attribute

model: Model | str | None = None

Model alias this agent uses. If omitted, inherits the parent's model.

name instance-attribute

name: str

Agent type identifier (e.g., "Explore").

AgentInput

Bases: TypedDict

Input for the Task tool. Launches a new agent to handle complex, multi-step tasks.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class AgentInput(TypedDict):
    """Input for the Task tool. Launches a new agent to handle complex, multi-step tasks."""

    description: str
    """A short (3-5 word) description of the task."""
    prompt: str
    """The task for the agent to perform."""
    subagent_type: NotRequired[str]
    """The type of specialized agent to use for this task."""
    model: NotRequired[ModelName]
    """Optional model override for this agent.

    Takes precedence over the agent definition's model frontmatter.
    If omitted, uses the agent definition's model, or inherits from the parent."""
    # resume: NotRequired[str]
    # """Optional agent ID to resume from in order to continue from the previous exec transcript."""
    run_in_background: NotRequired[bool]
    """Whether to run the agent in the background."""
    name: NotRequired[str]
    """Name for the spawned agent."""
    team_name: NotRequired[str]
    """Team name for spawning. Uses current team context if omitted."""
    mode: NotRequired[PermissionMode]
    """Deprecated; ignored. Subagents inherit the parent session's permission mode."""
    effort: NotRequired[ReasoningEffort]
    """Reasoning effort for this agent."""
    isolation: NotRequired[Literal["worktree", "remote"]]
    """Isolation mode.

    "worktree" creates a temporary git worktree; "remote" launches the agent in a
    remote cloud environment (always runs in background)."""

description instance-attribute

description: str

A short (3-5 word) description of the task.

effort instance-attribute

effort: NotRequired[ReasoningEffort]

Reasoning effort for this agent.

isolation instance-attribute

isolation: NotRequired[Literal['worktree', 'remote']]

Isolation mode.

"worktree" creates a temporary git worktree; "remote" launches the agent in a remote cloud environment (always runs in background).

mode instance-attribute

mode: NotRequired[PermissionMode]

Deprecated; ignored. Subagents inherit the parent session's permission mode.

model instance-attribute

model: NotRequired[ModelName]

Optional model override for this agent.

Takes precedence over the agent definition's model frontmatter. If omitted, uses the agent definition's model, or inherits from the parent.

name instance-attribute

name: NotRequired[str]

Name for the spawned agent.

prompt instance-attribute

prompt: str

The task for the agent to perform.

run_in_background instance-attribute

run_in_background: NotRequired[bool]

Whether to run the agent in the background.

subagent_type instance-attribute

subagent_type: NotRequired[str]

The type of specialized agent to use for this task.

team_name instance-attribute

team_name: NotRequired[str]

Team name for spawning. Uses current team context if omitted.

AgentOutputTextContent

Bases: TypedDict

A text content block in agent output.

Source code in src/clawd_code_sdk/models/output_types.py
class AgentOutputTextContent(TypedDict):
    """A text content block in agent output."""

    type: Literal["text"]
    """Content type, always 'text'."""
    text: str
    """The text content."""
    citations: NotRequired[list[Any] | None]
    """Citations attached to the text block."""

citations instance-attribute

citations: NotRequired[list[Any] | None]

Citations attached to the text block.

text instance-attribute

text: str

The text content.

type instance-attribute

type: Literal['text']

Content type, always 'text'.

AgentOutputUsage

Bases: TypedDict

Token usage statistics from an agent task.

Source code in src/clawd_code_sdk/models/output_types.py
class AgentOutputUsage(TypedDict):
    """Token usage statistics from an agent task."""

    input_tokens: int
    """Number of input tokens consumed."""
    output_tokens: int
    """Number of output tokens generated."""
    cache_creation_input_tokens: int | None
    """Tokens used to create cache entries."""
    cache_read_input_tokens: int | None
    """Tokens read from cache."""
    server_tool_use: AgentServerToolUse | None
    """Server-side tool usage statistics."""
    service_tier: ServiceTier | None
    """Service tier used for the request."""
    cache_creation: AgentCacheCreation | None
    """Cache creation statistics."""
    inference_geo: NotRequired[str | None]
    """Inference geography."""
    speed: NotRequired[str | None]
    """Speed mode."""
    iterations: NotRequired[Any]
    """Per-iteration usage."""
    output_tokens_details: NotRequired[AgentOutputTokensDetails | None]
    """Breakdown of output tokens."""
    fallback_credit: NotRequired[Any]
    """Fallback credit info."""

cache_creation instance-attribute

cache_creation: AgentCacheCreation | None

Cache creation statistics.

cache_creation_input_tokens instance-attribute

cache_creation_input_tokens: int | None

Tokens used to create cache entries.

cache_read_input_tokens instance-attribute

cache_read_input_tokens: int | None

Tokens read from cache.

fallback_credit instance-attribute

fallback_credit: NotRequired[Any]

Fallback credit info.

inference_geo instance-attribute

inference_geo: NotRequired[str | None]

Inference geography.

input_tokens instance-attribute

input_tokens: int

Number of input tokens consumed.

iterations instance-attribute

iterations: NotRequired[Any]

Per-iteration usage.

output_tokens instance-attribute

output_tokens: int

Number of output tokens generated.

output_tokens_details instance-attribute

output_tokens_details: NotRequired[AgentOutputTokensDetails | None]

Breakdown of output tokens.

server_tool_use instance-attribute

server_tool_use: AgentServerToolUse | None

Server-side tool usage statistics.

service_tier instance-attribute

service_tier: ServiceTier | None

Service tier used for the request.

speed instance-attribute

speed: NotRequired[str | None]

Speed mode.

AgentServerToolUse

Bases: TypedDict

Server-side tool usage statistics.

Source code in src/clawd_code_sdk/models/usage.py
class AgentServerToolUse(TypedDict):
    """Server-side tool usage statistics."""

    web_search_requests: int
    """Number of web search requests made."""
    web_fetch_requests: int
    """Number of web fetch requests made."""

web_fetch_requests instance-attribute

web_fetch_requests: int

Number of web fetch requests made.

web_search_requests instance-attribute

web_search_requests: int

Number of web search requests made.

AgentWireDefinition

Bases: ClaudeCodeBaseModel

Wire-format agent definition matching the CLI control protocol.

This is the strict camelCase representation sent over the wire in the initialize request.

The CLI's public Zod schema (sdk.d.ts) only defines::

description, prompt, tools, disallowedTools, model, mcpServers,
criticalSystemReminder_EXPERIMENTAL, skills, maxTurns

However, the CLI's internal parse schema (Rff / parseAgentFromJson) also accepts these additional fields, which are fully functional::

memory, background, hooks, effort, permissionMode, isolation
Source code in src/clawd_code_sdk/models/agents.py
class AgentWireDefinition(ClaudeCodeBaseModel):
    """Wire-format agent definition matching the CLI control protocol.

    This is the strict camelCase representation sent over the wire
    in the initialize request.

    The CLI's *public* Zod schema (``sdk.d.ts``) only defines::

        description, prompt, tools, disallowedTools, model, mcpServers,
        criticalSystemReminder_EXPERIMENTAL, skills, maxTurns

    However, the CLI's *internal* parse schema (``Rff`` / ``parseAgentFromJson``)
    also accepts these additional fields, which are fully functional::

        memory, background, hooks, effort, permissionMode, isolation
    """

    description: str
    prompt: str
    tools: list[ToolName | str] | None = None
    model: ModelName | Literal["inherit"] | str | None = None  # noqa: PYI051
    memory: SettingSource | None = None
    mcp_servers: Sequence[AgentMcpServerSpec] | None = None
    disallowed_tools: list[ToolName | str] | None = None
    critical_system_reminder_experimental: str | None = Field(
        default=None, serialization_alias="criticalSystemReminder_EXPERIMENTAL"
    )
    skills: list[str] | None = None
    initial_prompt: str | None = None
    max_turns: int | None = None
    background: bool | None = None
    hooks: AgentHooksConfig | None = None
    effort: ReasoningEffort | int | None = None
    permission_mode: PermissionMode | None = None
    isolation: Literal["worktree"] | None = None
    auto_compact_window: int | None = None
    omit_claude_md: bool | None = Field(default=None, serialization_alias="omitClaudeMd")
    observer: str | None = None
    observer_message: str | None = None

ApiErrorParams

Bases: ClaudeCodeBaseModel

Parameters of an API error, present only for the error kinds that have any (undocumented).

Source code in src/clawd_code_sdk/models/messages.py
class ApiErrorParams(ClaudeCodeBaseModel):
    """Parameters of an API error, present only for the error kinds that have any (undocumented)."""

    effort: str | None = None
    """Effort level the API refused (effort_requires_thinking)."""
    provider: (
        Literal[
            "bedrock",
            "anthropicAws",
            "mantle",
            "anthropicGoogleCloud",
            "vertex",
            "foundry",
            "gateway",
        ]
        | None
    ) = None
    remedy: (
        Literal[
            "refresh_command",
            "refresh_credentials",
            "adc",
            "gateway_token",
            "host_managed",
            "model_access",
        ]
        | None
    ) = None
    media: Literal["image", "document"] | None = None
    """Kind of block the API refused (media_removed)."""
    media_reason: Literal["unprocessable", "unsupported_by_model", "media_budget"] | None = None
    rate_limit_info: RateLimitInfo | None = None
    cut: Literal["output_limit", "context_window"] | None = None

effort class-attribute instance-attribute

effort: str | None = None

Effort level the API refused (effort_requires_thinking).

media class-attribute instance-attribute

media: Literal['image', 'document'] | None = None

Kind of block the API refused (media_removed).

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.

AskUserQuestion

Bases: TypedDict

A single question to ask the user.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class AskUserQuestion(TypedDict):
    """A single question to ask the user."""

    question: str
    """The complete question to ask. Should be clear, specific, and end with a question mark."""
    header: str
    """Very short label displayed as a chip/tag (max 12 chars)."""
    options: list[AskUserQuestionOption]
    """The available choices (2-4 options). An "Other" option is automatically provided."""
    multiSelect: bool
    """Set to true to allow multiple selections."""

header instance-attribute

header: str

Very short label displayed as a chip/tag (max 12 chars).

multiSelect instance-attribute

multiSelect: bool

Set to true to allow multiple selections.

options instance-attribute

options: list[AskUserQuestionOption]

The available choices (2-4 options). An "Other" option is automatically provided.

question instance-attribute

question: str

The complete question to ask. Should be clear, specific, and end with a question mark.

AskUserQuestionInput

Bases: TypedDict

Input for the AskUserQuestion tool.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class AskUserQuestionInput(TypedDict):
    """Input for the AskUserQuestion tool."""

    questions: list[AskUserQuestion]
    """Questions to ask the user (1-4 questions)."""
    answers: NotRequired[dict[str, str]]
    """User answers populated by the permission system.

    Maps question text to selected option label(s).
    Multi-select answers are comma-separated.
    """

answers instance-attribute

answers: NotRequired[dict[str, str]]

User answers populated by the permission system.

Maps question text to selected option label(s). Multi-select answers are comma-separated.

questions instance-attribute

questions: list[AskUserQuestion]

Questions to ask the user (1-4 questions).

AskUserQuestionItem

Bases: TypedDict

A single question that was asked.

Source code in src/clawd_code_sdk/models/output_types.py
class AskUserQuestionItem(TypedDict):
    """A single question that was asked."""

    question: str
    header: str
    options: list[AskUserQuestionOption]
    multiSelect: bool

AskUserQuestionOption

Bases: TypedDict

A single option for a user question.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class AskUserQuestionOption(TypedDict):
    """A single option for a user question."""

    label: str
    """Display text for this option (1-5 words)."""
    description: str
    """Explanation of what this option means."""
    preview: NotRequired[str]
    """Optional preview content rendered when this option is focused."""

description instance-attribute

description: str

Explanation of what this option means.

label instance-attribute

label: str

Display text for this option (1-5 words).

preview instance-attribute

preview: NotRequired[str]

Optional preview content rendered when this option is focused.

AskUserQuestionOutput

Bases: TypedDict

tool_use_result for the AskUserQuestion tool.

Source code in src/clawd_code_sdk/models/output_types.py
class AskUserQuestionOutput(TypedDict):
    """``tool_use_result`` for the AskUserQuestion tool."""

    questions: list[AskUserQuestionItem]
    """The questions that were asked."""

    answers: dict[str, str]
    """Maps question text to answer string. Multi-select answers are comma-separated."""
    response: NotRequired[str]
    """Free-text response from the user."""
    annotations: NotRequired[dict[str, AskUserQuestionAnnotation]]
    """Per-question annotations from the user, keyed by question text."""
    afkTimeoutMs: NotRequired[float]
    """Set when the question timed out because the user was away (ms)."""

afkTimeoutMs instance-attribute

afkTimeoutMs: NotRequired[float]

Set when the question timed out because the user was away (ms).

annotations instance-attribute

annotations: NotRequired[dict[str, AskUserQuestionAnnotation]]

Per-question annotations from the user, keyed by question text.

answers instance-attribute

answers: dict[str, str]

Maps question text to answer string. Multi-select answers are comma-separated.

questions instance-attribute

questions: list[AskUserQuestionItem]

The questions that were asked.

response instance-attribute

response: NotRequired[str]

Free-text response from the user.

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)

AssistantMessageContent

Bases: ClaudeCodeBaseModel

Assistant message payload mirroring anthropic.types.beta.BetaMessage.

Uses our own ContentBlock types instead of the Anthropic SDK's BetaContentBlock variants. Extra fields from the wire format (e.g. container, context_management) are preserved via extra="allow".

Source code in src/clawd_code_sdk/models/content_blocks.py
class AssistantMessageContent(ClaudeCodeBaseModel):
    """Assistant message payload mirroring ``anthropic.types.beta.BetaMessage``.

    Uses our own ``ContentBlock`` types instead of the Anthropic SDK's
    ``BetaContentBlock`` variants. Extra fields from the wire format
    (e.g. ``container``, ``context_management``) are preserved via ``extra="allow"``.
    """

    id: str
    type: Literal["message"] = "message"
    role: Literal["assistant"] = "assistant"
    content: Sequence[AssistantContentBlock]
    model: Model | str
    stop_reason: StopReason | None = None
    stop_sequence: str | None = None
    model_config = ConfigDict(extra="allow")

AsyncHookJSONOutput

Bases: TypedDict

Async hook output that defers hook execution.

Fields

async_: Set to True to defer hook execution. Note: This is converted to "async" when sent to the CLI - use "async_" in your Python code. asyncTimeout: Optional timeout in milliseconds for the async operation.

Source code in src/clawd_code_sdk/models/hooks.py
class AsyncHookJSONOutput(TypedDict):
    """Async hook output that defers hook execution.

    Fields:
        async_: Set to True to defer hook execution. Note: This is converted to
            "async" when sent to the CLI - use "async_" in your Python code.
        asyncTimeout: Optional timeout in milliseconds for the async operation.
    """

    async_: Literal[True]  # Using async_ to avoid Python keyword (converted to "async" for CLI)
    asyncTimeout: NotRequired[int]

AuthStatusMessage

Bases: BaseMessage

Authentication status update.

Source code in src/clawd_code_sdk/models/messages.py
class AuthStatusMessage(BaseMessage):
    """Authentication status update."""

    type: Literal["auth_status"] = "auth_status"
    session_id: str
    is_authenticating: bool = Field(False, validation_alias="isAuthenticating")
    output: list[str] | None = None
    error: str | None = None

BackgroundTasksChangedMessage

Bases: BaseSystemMessage

Full snapshot of running background tasks, emitted whenever the set changes.

Source code in src/clawd_code_sdk/models/system_messages.py
class BackgroundTasksChangedMessage(BaseSystemMessage):
    """Full snapshot of running background tasks, emitted whenever the set changes."""

    subtype: Literal["background_tasks_changed"] = "background_tasks_changed"
    tasks: list[BackgroundTask]

Base64PDFSource

Bases: BaseContentBlock

Base64-encoded PDF document.

Source code in src/clawd_code_sdk/models/content_blocks.py
class Base64PDFSource(BaseContentBlock):
    """Base64-encoded PDF document."""

    type: Literal["base64"] = "base64"
    media_type: Literal["application/pdf"] = "application/pdf"
    data: str

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.

BaseSessionConfig dataclass

Common fields for all session configurations.

Source code in src/clawd_code_sdk/models/options.py
@dataclass(kw_only=True)
class BaseSessionConfig:
    """Common fields for all session configurations."""

    persist: bool = True
    """Whether to persist the session to disk."""

persist class-attribute instance-attribute

persist: bool = True

Whether to persist the session to disk.

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

BashInput

Bases: TypedDict

Input for the Bash tool. Executes bash commands in a persistent shell session.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class BashInput(TypedDict):
    """Input for the Bash tool. Executes bash commands in a persistent shell session."""

    command: str
    """The command to execute."""
    timeout: NotRequired[int]
    """Optional timeout in milliseconds (max 600000)."""
    description: NotRequired[str]
    """Clear, concise description of what this command does in 5-10 words."""
    run_in_background: NotRequired[bool]
    """Set to true to run this command in the background."""

command instance-attribute

command: str

The command to execute.

description instance-attribute

description: NotRequired[str]

Clear, concise description of what this command does in 5-10 words.

run_in_background instance-attribute

run_in_background: NotRequired[bool]

Set to true to run this command in the background.

timeout instance-attribute

timeout: NotRequired[int]

Optional timeout in milliseconds (max 600000).

BashOutput

Bases: TypedDict

tool_use_result for the Bash tool.

Source code in src/clawd_code_sdk/models/output_types.py
class BashOutput(TypedDict):
    """``tool_use_result`` for the Bash tool."""

    stdout: str
    """Standard output from the command."""
    stderr: str
    """Standard error from the command."""
    interrupted: bool
    """Whether the command was interrupted."""
    isImage: NotRequired[bool]
    """Whether the output is an image."""
    noOutputExpected: NotRequired[bool]
    """Whether the command is expected to produce no output on success."""
    backgroundTaskId: NotRequired[str]
    """Task ID when ``run_in_background=true`` was used."""
    backgroundedByUser: NotRequired[bool]
    """True if the user manually backgrounded the command with Ctrl+B."""
    rawOutputPath: NotRequired[str]
    """Path to raw output file for large MCP tool outputs."""
    dangerouslyDisableSandbox: NotRequired[bool]
    """Whether sandbox mode was overridden."""
    returnCodeInterpretation: NotRequired[str]
    """Semantic interpretation for non-error exit codes with special meaning."""
    structuredContent: NotRequired[list[Any]]
    """Structured content blocks."""
    persistedOutputPath: NotRequired[str]
    """Path to persisted full output (when output is too large for inline)."""
    persistedOutputSize: NotRequired[int]
    """Total size of the output in bytes (when output is too large for inline)."""
    staleReadFileStateHint: NotRequired[str]
    """Model-facing note listing readFileState entries whose mtime bumped during this command."""
    # tokenSaverOutput: NotRequired[str]
    # """Compressed output sent to model when token-saver is active (UI still uses stdout)."""
    ghRateLimitHint: NotRequired[str]
    """Model-facing sys-reminder appended when a gh cmd reports a GitHub API rate-limit error."""
    timedOutAfterMs: NotRequired[float]
    """Set when the command hit its timeout and was auto-backgrounded; the timeout in ms."""
    backgroundCwdHint: NotRequired[str]
    """Note that the session cwd was not changed by a backgrounded directory-change command."""
    backgroundEndsWithFinalResponse: NotRequired[Literal[True]]
    """True when this backgrounded command is terminated at its caller's final response."""
    backgroundWakesOwner: NotRequired[Literal[True]]
    """True when the subagent owning this backgrounded command is woken by its end."""
    gitOperation: NotRequired[BashGitOperation]
    """Structured classification of git/gh operations detected in this command."""

backgroundCwdHint instance-attribute

backgroundCwdHint: NotRequired[str]

Note that the session cwd was not changed by a backgrounded directory-change command.

backgroundEndsWithFinalResponse instance-attribute

backgroundEndsWithFinalResponse: NotRequired[Literal[True]]

True when this backgrounded command is terminated at its caller's final response.

backgroundTaskId instance-attribute

backgroundTaskId: NotRequired[str]

Task ID when run_in_background=true was used.

backgroundWakesOwner instance-attribute

backgroundWakesOwner: NotRequired[Literal[True]]

True when the subagent owning this backgrounded command is woken by its end.

backgroundedByUser instance-attribute

backgroundedByUser: NotRequired[bool]

True if the user manually backgrounded the command with Ctrl+B.

dangerouslyDisableSandbox instance-attribute

dangerouslyDisableSandbox: NotRequired[bool]

Whether sandbox mode was overridden.

ghRateLimitHint instance-attribute

ghRateLimitHint: NotRequired[str]

Model-facing sys-reminder appended when a gh cmd reports a GitHub API rate-limit error.

gitOperation instance-attribute

gitOperation: NotRequired[BashGitOperation]

Structured classification of git/gh operations detected in this command.

interrupted instance-attribute

interrupted: bool

Whether the command was interrupted.

isImage instance-attribute

isImage: NotRequired[bool]

Whether the output is an image.

noOutputExpected instance-attribute

noOutputExpected: NotRequired[bool]

Whether the command is expected to produce no output on success.

persistedOutputPath instance-attribute

persistedOutputPath: NotRequired[str]

Path to persisted full output (when output is too large for inline).

persistedOutputSize instance-attribute

persistedOutputSize: NotRequired[int]

Total size of the output in bytes (when output is too large for inline).

rawOutputPath instance-attribute

rawOutputPath: NotRequired[str]

Path to raw output file for large MCP tool outputs.

returnCodeInterpretation instance-attribute

returnCodeInterpretation: NotRequired[str]

Semantic interpretation for non-error exit codes with special meaning.

staleReadFileStateHint instance-attribute

staleReadFileStateHint: NotRequired[str]

Model-facing note listing readFileState entries whose mtime bumped during this command.

stderr instance-attribute

stderr: str

Standard error from the command.

stdout instance-attribute

stdout: str

Standard output from the command.

structuredContent instance-attribute

structuredContent: NotRequired[list[Any]]

Structured content blocks.

timedOutAfterMs instance-attribute

timedOutAfterMs: NotRequired[float]

Set when the command hit its timeout and was auto-backgrounded; the timeout in ms.

BashOutputInput

Bases: TypedDict

Input for the BashOutput tool. Retrieves output from a background bash shell.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class BashOutputInput(TypedDict):
    """Input for the BashOutput tool. Retrieves output from a background bash shell."""

    bash_id: str
    """The ID of the background shell to retrieve output from."""
    filter: NotRequired[str]
    """Optional regex to filter output lines."""

bash_id instance-attribute

bash_id: str

The ID of the background shell to retrieve output from.

filter instance-attribute

filter: NotRequired[str]

Optional regex to filter output lines.

BashOutputOutput

Bases: TypedDict

tool_use_result for the BashOutput tool (background shell output retrieval).

Not part of the official SDK ToolOutputSchemas as of SDK v0.2.62. Shape derived from: https://github.com/kzahel/yepanywhere/blob/main/packages/shared/src/claude-sdk-schema/tool/ToolResultSchemas.ts

Source code in src/clawd_code_sdk/models/output_types.py
class BashOutputOutput(TypedDict):
    """``tool_use_result`` for the BashOutput tool (background shell output retrieval).

    Not part of the official SDK ToolOutputSchemas as of SDK v0.2.62.
    Shape derived from: https://github.com/kzahel/yepanywhere/blob/main/packages/shared/src/claude-sdk-schema/tool/ToolResultSchemas.ts
    """

    shellId: NotRequired[str]
    """ID of the background shell."""
    command: NotRequired[str]
    """The command that was executed."""
    status: NotRequired[Status]
    """Current status of the command."""
    exitCode: NotRequired[int | None]
    """Exit code of the command, or None if still running."""
    stdout: NotRequired[str]
    """Standard output."""
    stderr: NotRequired[str]
    """Standard error."""
    stdoutLines: NotRequired[int]
    """Number of lines in stdout."""
    stderrLines: NotRequired[int]
    """Number of lines in stderr."""
    timestamp: NotRequired[str]
    """Timestamp of the output."""

command instance-attribute

command: NotRequired[str]

The command that was executed.

exitCode instance-attribute

exitCode: NotRequired[int | None]

Exit code of the command, or None if still running.

shellId instance-attribute

shellId: NotRequired[str]

ID of the background shell.

status instance-attribute

status: NotRequired[Status]

Current status of the command.

stderr instance-attribute

stderr: NotRequired[str]

Standard error.

stderrLines instance-attribute

stderrLines: NotRequired[int]

Number of lines in stderr.

stdout instance-attribute

stdout: NotRequired[str]

Standard output.

stdoutLines instance-attribute

stdoutLines: NotRequired[int]

Number of lines in stdout.

timestamp instance-attribute

timestamp: NotRequired[str]

Timestamp of the output.

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

ClaudeCodeAgentInfo

Bases: ClaudeCodeBaseModel

Information about an available subagent from Claude Code server.

Source code in src/clawd_code_sdk/models/server_info.py
class ClaudeCodeAgentInfo(ClaudeCodeBaseModel):
    """Information about an available subagent from Claude Code server."""

    name: str
    """Agent type identifier (e.g., "Explore")."""

    description: str
    """Description of when to use this agent."""

    model: Model | str | None = None
    """Model alias this agent uses. If omitted, inherits the parent's model."""

description instance-attribute

description: str

Description of when to use this agent.

model class-attribute instance-attribute

model: Model | str | None = None

Model alias this agent uses. If omitted, inherits the parent's model.

name instance-attribute

name: str

Agent type identifier (e.g., "Explore").

ClaudeCodeCommandInfo

Bases: ClaudeCodeBaseModel

Information about an available slash command from Claude Code.

Source code in src/clawd_code_sdk/models/server_info.py
class ClaudeCodeCommandInfo(ClaudeCodeBaseModel):
    """Information about an available slash command from Claude Code."""

    name: str
    """Command name without the / prefix (e.g., "compact", "review")."""

    description: str
    """Full description of what the command does."""

    argument_hint: str
    """Usage hint for command arguments (may be empty string)."""

    aliases: list[str] | None = None
    """Alternate names that resolve to the command (e.g., /cost / /stats both resolve to /usage)."""

    builtin: bool | None = None
    """Whether this is a built-in command (as opposed to a skill/plugin/custom command)."""

aliases class-attribute instance-attribute

aliases: list[str] | None = None

Alternate names that resolve to the command (e.g., /cost / /stats both resolve to /usage).

argument_hint instance-attribute

argument_hint: str

Usage hint for command arguments (may be empty string).

builtin class-attribute instance-attribute

builtin: bool | None = None

Whether this is a built-in command (as opposed to a skill/plugin/custom command).

description instance-attribute

description: str

Full description of what the command does.

name instance-attribute

name: str

Command name without the / prefix (e.g., "compact", "review").

ClaudeCodeModelInfo

Bases: ClaudeCodeBaseModel

Information about an available AI model from Claude Code.

Source code in src/clawd_code_sdk/models/server_info.py
class ClaudeCodeModelInfo(ClaudeCodeBaseModel):
    """Information about an available AI model from Claude Code."""

    value: str
    """Model identifier used in API calls (e.g., "default", "opus", "haiku")."""

    display_name: str
    """Human-readable display name (e.g., "Opus", "Default (recommended)")."""

    description: str
    """Full description including capabilities and pricing."""

    supports_effort: bool | None = None
    """Whether the model supports effort setting."""

    supported_effort_levels: list[EffortLevel] | None = None
    """Supported effort levels."""

    supports_adaptive_thinking: bool | None = None
    """Whether the model supports adaptive thinking."""

    supports_fast_mode: bool | None = None
    """Whether the model supports fast mode."""

    supports_auto_mode: bool | None = None
    """Whether the model supports auto mode."""

    supports_thinking_off: bool | None = None
    """Whether thinking can be turned off for the model."""

    disabled: bool | None = None
    """Visible but not selectable (only set for entries in ``unavailable_models``)."""

    resolved_model: str | None = None
    """Concrete model ID this entry resolves to (e.g. for aliases)."""

description instance-attribute

description: str

Full description including capabilities and pricing.

disabled class-attribute instance-attribute

disabled: bool | None = None

Visible but not selectable (only set for entries in unavailable_models).

display_name instance-attribute

display_name: str

Human-readable display name (e.g., "Opus", "Default (recommended)").

resolved_model class-attribute instance-attribute

resolved_model: str | None = None

Concrete model ID this entry resolves to (e.g. for aliases).

supported_effort_levels class-attribute instance-attribute

supported_effort_levels: list[EffortLevel] | None = None

Supported effort levels.

supports_adaptive_thinking class-attribute instance-attribute

supports_adaptive_thinking: bool | None = None

Whether the model supports adaptive thinking.

supports_auto_mode class-attribute instance-attribute

supports_auto_mode: bool | None = None

Whether the model supports auto mode.

supports_effort class-attribute instance-attribute

supports_effort: bool | None = None

Whether the model supports effort setting.

supports_fast_mode class-attribute instance-attribute

supports_fast_mode: bool | None = None

Whether the model supports fast mode.

supports_thinking_off class-attribute instance-attribute

supports_thinking_off: bool | None = None

Whether thinking can be turned off for the model.

value instance-attribute

value: str

Model identifier used in API calls (e.g., "default", "opus", "haiku").

ClaudeCodeServerInfo

Bases: ClaudeCodeBaseModel

Complete server initialization info from Claude Code.

This is returned by the Claude Code server during initialization and contains all available capabilities including models, commands, output styles, and account information.

Source code in src/clawd_code_sdk/models/server_info.py
class ClaudeCodeServerInfo(ClaudeCodeBaseModel):
    """Complete server initialization info from Claude Code.

    This is returned by the Claude Code server during initialization and contains
    all available capabilities including models, commands, output styles, and
    account information.
    """

    models: list[ClaudeCodeModelInfo] = Field(default_factory=list)
    """List of available AI models."""

    commands: list[ClaudeCodeCommandInfo] = Field(default_factory=list)
    """List of available slash commands."""

    output_style: str = Field(default="default")
    """Current output style setting."""

    available_output_styles: list[str] = Field(default_factory=list)
    """List of all available output styles."""

    unavailable_models: list[ClaudeCodeModelInfo] | None = None
    """Models the account can see but not select (e.g. excluded by org ZDR settings)."""

    account: ClaudeCodeAccountInfo | None = Field(default=None)
    """Account and authentication information."""

    auth_conflict: AuthConflict | None = None
    """Set when both an auth token and an API key are configured (source names only)."""

    current_model: str | None = None
    """The CLI's active model at connect time."""

    agents: list[ClaudeCodeAgentInfo] = Field(default_factory=list)
    """List of available subagents."""

    fast_mode_state: FastModeState | None = None
    """Fast mode state: off, in cooldown after rate limit, or actively enabled."""

    fast_mode_disabled_reason: FastModeDisabledReason | None = None
    """Why fast mode is unavailable, if it is."""

    claude_code_version: str | None = None
    """Version of the Claude Code process answering initialize."""

    capabilities: list[str] | None = None
    """Feature capability tags supported by the CLI (undocumented, informational)."""

    current_permission_mode: str | None = None
    """Permission mode the session is currently in (undocumented)."""

    session_state: str | None = None
    """Current session state, e.g. "idle" (undocumented)."""

    user_output_styles_dir: str | None = None
    """Directory for user-defined output styles (undocumented)."""

    feedback_mode: FeedbackMode | None = None
    """How the CLI collects feedback (undocumented)."""

    analytics_disabled: bool | None = None
    other_hook_ask_outranks_host: bool | None = None
    remote_control_available: bool | None = None
    remote_control_auto_enable: bool | None = None
    remote_control_auto_connect_default: bool | None = None
    remote_control_auto_on_by_default: bool | None = None
    ide_rc_auto_enable_gate: bool | None = None

    hooks_applied: bool | None = None
    """False when the process was already running and did not register SDK hooks."""

    hook_on_failure_supported: bool | None = None
    """Whether the CLI honors ``on_failure`` on hook matchers."""

    hooks_when_unanswered_kept: int | None = None
    """Number of registered hook matchers whose ``whenUnanswered`` the CLI kept."""

    code_running_mcp_tools_applied: dict[str, list[str]] | None = None
    """MCP tools declared via ``codeRunningMcpTools``, keyed by server name."""

    managed_settings_applied: bool | None = None
    """Whether the initialize's ``managedSettings`` match the ones stored at launch."""

    mcp_servers_applied: bool | None = None
    """Whether the initialize's ``mcpServers`` match the set read at launch."""

    host_worded_asks: bool | None = None
    """Desktop host only: PreToolUse asks are sent to the host as can_use_tool requests."""

    workspace_trust_recorded: bool | None = None
    """Outcome of the ``workspaceTrust`` attestation."""

    inbound_read_receipts: bool | None = None
    """Remote Control hosts only: client messages get processing/processed receipts."""

    permission_mode_from_default_fallback: bool | None = None
    """IDE hosts only: permission mode is auto because no settings source configured one."""

    auto_default_nudge: str | None = None
    """IDE hosts only: the defaultMode the auto-default nudge offers to replace."""

    footer_indicator: dict[str, Any] | None = None
    """The terminal's configured footer pill (undocumented structure)."""

    feedback_survey_config: dict[str, Any] | None = None
    """Present only when the host may show the feedback survey (undocumented structure)."""

    survey_followup_box: dict[str, Any] | None = None
    """Survey follow-up config for VS Code/desktop hosts (undocumented structure)."""

    claude_in_chrome_at_startup: bool | None = None
    """Whether an IDE host should connect Claude in Chrome when the session starts."""

    claude_in_chrome_prompt_disabled: bool | None = None
    """True when CLAUDE_CODE_DISABLE_CFC_PROMPT is set."""

    plugins_applied: bool | None = None
    """Whether every plugin sent via initialize is loaded."""

    sdk_mcp_manifests_parked: (
        dict[
            str,
            Literal[
                "parked",
                "already_connected",
                "protocol_version_mismatch",
                "malformed",
                "not_honoured",
            ],
        ]
        | None
    ) = None

    pid: int | None = None
    """Process id."""

account class-attribute instance-attribute

account: ClaudeCodeAccountInfo | None = Field(default=None)

Account and authentication information.

agents class-attribute instance-attribute

agents: list[ClaudeCodeAgentInfo] = Field(default_factory=list)

List of available subagents.

auth_conflict class-attribute instance-attribute

auth_conflict: AuthConflict | None = None

Set when both an auth token and an API key are configured (source names only).

auto_default_nudge class-attribute instance-attribute

auto_default_nudge: str | None = None

IDE hosts only: the defaultMode the auto-default nudge offers to replace.

available_output_styles class-attribute instance-attribute

available_output_styles: list[str] = Field(default_factory=list)

List of all available output styles.

capabilities class-attribute instance-attribute

capabilities: list[str] | None = None

Feature capability tags supported by the CLI (undocumented, informational).

claude_code_version class-attribute instance-attribute

claude_code_version: str | None = None

Version of the Claude Code process answering initialize.

claude_in_chrome_at_startup class-attribute instance-attribute

claude_in_chrome_at_startup: bool | None = None

Whether an IDE host should connect Claude in Chrome when the session starts.

claude_in_chrome_prompt_disabled class-attribute instance-attribute

claude_in_chrome_prompt_disabled: bool | None = None

True when CLAUDE_CODE_DISABLE_CFC_PROMPT is set.

code_running_mcp_tools_applied class-attribute instance-attribute

code_running_mcp_tools_applied: dict[str, list[str]] | None = None

MCP tools declared via codeRunningMcpTools, keyed by server name.

commands class-attribute instance-attribute

commands: list[ClaudeCodeCommandInfo] = Field(default_factory=list)

List of available slash commands.

current_model class-attribute instance-attribute

current_model: str | None = None

The CLI's active model at connect time.

current_permission_mode class-attribute instance-attribute

current_permission_mode: str | None = None

Permission mode the session is currently in (undocumented).

fast_mode_disabled_reason class-attribute instance-attribute

fast_mode_disabled_reason: FastModeDisabledReason | None = None

Why fast mode is unavailable, if it is.

fast_mode_state class-attribute instance-attribute

fast_mode_state: FastModeState | None = None

Fast mode state: off, in cooldown after rate limit, or actively enabled.

feedback_mode class-attribute instance-attribute

feedback_mode: FeedbackMode | None = None

How the CLI collects feedback (undocumented).

feedback_survey_config class-attribute instance-attribute

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

Present only when the host may show the feedback survey (undocumented structure).

footer_indicator class-attribute instance-attribute

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

The terminal's configured footer pill (undocumented structure).

hook_on_failure_supported class-attribute instance-attribute

hook_on_failure_supported: bool | None = None

Whether the CLI honors on_failure on hook matchers.

hooks_applied class-attribute instance-attribute

hooks_applied: bool | None = None

False when the process was already running and did not register SDK hooks.

hooks_when_unanswered_kept class-attribute instance-attribute

hooks_when_unanswered_kept: int | None = None

Number of registered hook matchers whose whenUnanswered the CLI kept.

host_worded_asks class-attribute instance-attribute

host_worded_asks: bool | None = None

Desktop host only: PreToolUse asks are sent to the host as can_use_tool requests.

inbound_read_receipts class-attribute instance-attribute

inbound_read_receipts: bool | None = None

Remote Control hosts only: client messages get processing/processed receipts.

managed_settings_applied class-attribute instance-attribute

managed_settings_applied: bool | None = None

Whether the initialize's managedSettings match the ones stored at launch.

mcp_servers_applied class-attribute instance-attribute

mcp_servers_applied: bool | None = None

Whether the initialize's mcpServers match the set read at launch.

models class-attribute instance-attribute

models: list[ClaudeCodeModelInfo] = Field(default_factory=list)

List of available AI models.

output_style class-attribute instance-attribute

output_style: str = Field(default='default')

Current output style setting.

permission_mode_from_default_fallback class-attribute instance-attribute

permission_mode_from_default_fallback: bool | None = None

IDE hosts only: permission mode is auto because no settings source configured one.

pid class-attribute instance-attribute

pid: int | None = None

Process id.

plugins_applied class-attribute instance-attribute

plugins_applied: bool | None = None

Whether every plugin sent via initialize is loaded.

session_state class-attribute instance-attribute

session_state: str | None = None

Current session state, e.g. "idle" (undocumented).

survey_followup_box class-attribute instance-attribute

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

Survey follow-up config for VS Code/desktop hosts (undocumented structure).

unavailable_models class-attribute instance-attribute

unavailable_models: list[ClaudeCodeModelInfo] | None = None

Models the account can see but not select (e.g. excluded by org ZDR settings).

user_output_styles_dir class-attribute instance-attribute

user_output_styles_dir: str | None = None

Directory for user-defined output styles (undocumented).

workspace_trust_recorded class-attribute instance-attribute

workspace_trust_recorded: bool | None = None

Outcome of the workspaceTrust attestation.

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

ClaudeOAuthWaitForCompletionResponse

Bases: ClaudeCodeBaseModel

Response from waiting for a Claude OAuth flow to complete.

Source code in src/clawd_code_sdk/models/control.py
class ClaudeOAuthWaitForCompletionResponse(ClaudeCodeBaseModel):
    """Response from waiting for a Claude OAuth flow to complete."""

    account: ClaudeCodeAccountInfo
    """Authenticated account details."""

account instance-attribute

Authenticated account details.

CommandLifecycleMessage

Bases: BaseMessage

Progress of a user message that was sent with a uuid (capability msg_lifecycle_v1).

queued: waiting behind the running work. started: taken in (the cycle it starts, or the running cycle it was folded into). completed: its work ended (after the result for a message that started a cycle, before it for one folded into a cycle). cancelled: an interrupt stopped it. discarded / refused: dropped before it ran.

Source code in src/clawd_code_sdk/models/messages.py
class CommandLifecycleMessage(BaseMessage):
    """Progress of a user message that was sent with a ``uuid`` (capability ``msg_lifecycle_v1``).

    ``queued``: waiting behind the running work. ``started``: taken in (the cycle it starts,
    or the running cycle it was folded into). ``completed``: its work ended (after the
    result for a message that started a cycle, before it for one folded into a cycle).
    ``cancelled``: an interrupt stopped it. ``discarded`` / ``refused``: dropped before it ran.
    """

    type: Literal["command_lifecycle"] = "command_lifecycle"
    command_uuid: str
    """The ``uuid`` the message was sent with."""
    state: CommandLifecycleState
    session_id: str

command_uuid instance-attribute

command_uuid: str

The uuid the message was sent with.

CommandsChangedMessage

Bases: BaseSystemMessage

Emitted when the set of available slash commands changes.

Source code in src/clawd_code_sdk/models/system_messages.py
class CommandsChangedMessage(BaseSystemMessage):
    """Emitted when the set of available slash commands changes."""

    subtype: Literal["commands_changed"] = "commands_changed"
    commands: list[ClaudeCodeCommandInfo]

CompactBoundarySystemMessage

Bases: BaseSystemMessage

System message emitted at compaction boundaries.

Source code in src/clawd_code_sdk/models/system_messages.py
class CompactBoundarySystemMessage(BaseSystemMessage):
    """System message emitted at compaction boundaries."""

    subtype: Literal["compact_boundary"] = "compact_boundary"
    compact_metadata: TriggerMetadata

ConfigOutput

Bases: TypedDict

Output from the Config tool.

Source code in src/clawd_code_sdk/models/output_types.py
class ConfigOutput(TypedDict):
    """Output from the Config tool."""

    success: bool
    """Whether the operation succeeded."""
    operation: NotRequired[Literal["get", "set"]]
    """The config operation that was performed."""
    setting: NotRequired[str]
    """The setting name."""
    value: NotRequired[Any]
    """The current or requested value."""
    previousValue: NotRequired[Any]
    """The previous value (for set operations)."""
    newValue: NotRequired[Any]
    """The new value (for set operations)."""
    error: NotRequired[str]
    """Error message if the operation failed."""

error instance-attribute

error: NotRequired[str]

Error message if the operation failed.

newValue instance-attribute

newValue: NotRequired[Any]

The new value (for set operations).

operation instance-attribute

operation: NotRequired[Literal['get', 'set']]

The config operation that was performed.

previousValue instance-attribute

previousValue: NotRequired[Any]

The previous value (for set operations).

setting instance-attribute

setting: NotRequired[str]

The setting name.

success instance-attribute

success: bool

Whether the operation succeeded.

value instance-attribute

value: NotRequired[Any]

The current or requested value.

ContentDocumentSource

Bases: BaseContentBlock

Document made of content blocks (text / images).

Source code in src/clawd_code_sdk/models/content_blocks.py
class ContentDocumentSource(BaseContentBlock):
    """Document made of content blocks (text / images)."""

    type: Literal["content"] = "content"
    content: str | list[dict[str, Any]]

ContextUsageAgent

Bases: ClaudeCodeBaseModel

An agent contributing to context usage.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageAgent(ClaudeCodeBaseModel):
    """An agent contributing to context usage."""

    agent_type: str
    source: str
    plugin_id: str | None = None
    path: str | None = None
    tokens: int

ContextUsageAttachmentBreakdown

Bases: ClaudeCodeBaseModel

Token breakdown for a specific attachment type.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageAttachmentBreakdown(ClaudeCodeBaseModel):
    """Token breakdown for a specific attachment type."""

    name: str
    tokens: int

ContextUsageCategory

Bases: ClaudeCodeBaseModel

A single category in the context usage breakdown.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageCategory(ClaudeCodeBaseModel):
    """A single category in the context usage breakdown."""

    id: ContextUsageCategoryId | None = None
    name: str
    tokens: int
    color: str
    is_deferred: bool | None = None
    kind: ContextUsageKind | None = None

ContextUsageDeferredBuiltinTool

Bases: ClaudeCodeBaseModel

A deferred builtin tool contributing to context usage.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageDeferredBuiltinTool(ClaudeCodeBaseModel):
    """A deferred builtin tool contributing to context usage."""

    name: str
    tokens: int
    is_loaded: bool

ContextUsageGridCell

Bases: ClaudeCodeBaseModel

A single cell in the context usage grid visualization.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageGridCell(ClaudeCodeBaseModel):
    """A single cell in the context usage grid visualization."""

    color: str
    is_filled: bool
    category_name: str
    tokens: int
    percentage: float
    square_fullness: float

ContextUsageMcpInstructions

Bases: ClaudeCodeBaseModel

MCP server instructions contributing to context usage.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageMcpInstructions(ClaudeCodeBaseModel):
    """MCP server instructions contributing to context usage."""

    server_name: str
    tokens: int

ContextUsageMcpTool

Bases: ClaudeCodeBaseModel

An MCP tool contributing to context usage.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageMcpTool(ClaudeCodeBaseModel):
    """An MCP tool contributing to context usage."""

    name: str
    server_name: str
    tokens: int
    is_loaded: bool | None = None

ContextUsageMemoryFile

Bases: ClaudeCodeBaseModel

A memory file contributing to context usage.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageMemoryFile(ClaudeCodeBaseModel):
    """A memory file contributing to context usage."""

    path: str
    type: str
    tokens: int

ContextUsageMessageBreakdown

Bases: ClaudeCodeBaseModel

Breakdown of message tokens by category.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageMessageBreakdown(ClaudeCodeBaseModel):
    """Breakdown of message tokens by category."""

    tool_call_tokens: int
    tool_result_tokens: int
    attachment_tokens: int
    assistant_message_tokens: int
    user_message_tokens: int
    redirected_context_tokens: int
    unattributed_tokens: int
    tool_calls_by_type: list[ContextUsageToolCallBreakdown]
    attachments_by_type: list[ContextUsageAttachmentBreakdown]

ContextUsageSkillFrontmatter

Bases: ClaudeCodeBaseModel

A single skill's frontmatter contributing to context usage.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageSkillFrontmatter(ClaudeCodeBaseModel):
    """A single skill's frontmatter contributing to context usage."""

    name: str
    source: str
    plugin_name: str | None = None
    plugin_id: str | None = None
    path: str | None = None
    tokens: int

ContextUsageSkills

Bases: ClaudeCodeBaseModel

Skills context usage summary.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageSkills(ClaudeCodeBaseModel):
    """Skills context usage summary."""

    total_skills: int
    included_skills: int
    tokens: int
    skill_frontmatter: list[ContextUsageSkillFrontmatter]

ContextUsageSlashCommands

Bases: ClaudeCodeBaseModel

Slash commands context usage summary.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageSlashCommands(ClaudeCodeBaseModel):
    """Slash commands context usage summary."""

    total_commands: int
    included_commands: int
    tokens: int

ContextUsageSystemPromptSection

Bases: ClaudeCodeBaseModel

A system prompt section contributing to context usage.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageSystemPromptSection(ClaudeCodeBaseModel):
    """A system prompt section contributing to context usage."""

    name: str
    tokens: int

ContextUsageSystemTool

Bases: ClaudeCodeBaseModel

A system tool contributing to context usage.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageSystemTool(ClaudeCodeBaseModel):
    """A system tool contributing to context usage."""

    name: str
    tokens: int

ContextUsageToolCallBreakdown

Bases: ClaudeCodeBaseModel

Token breakdown for a specific tool call type.

Source code in src/clawd_code_sdk/models/context_usage.py
class ContextUsageToolCallBreakdown(ClaudeCodeBaseModel):
    """Token breakdown for a specific tool call type."""

    name: str
    call_tokens: int
    result_tokens: int

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.

ControlErrorResponse

Bases: TypedDict

Control Error response.

Source code in src/clawd_code_sdk/models/control.py
class ControlErrorResponse(TypedDict):
    """Control Error response."""

    subtype: Literal["error"]
    request_id: str
    error: str

ControlRequestProgressMessage

Bases: BaseSystemMessage

Progress for a long-running control request (e.g. side question).

Source code in src/clawd_code_sdk/models/system_messages.py
class ControlRequestProgressMessage(BaseSystemMessage):
    """Progress for a long-running control request (e.g. side question)."""

    subtype: Literal["control_request_progress"] = "control_request_progress"
    request_id: str
    status: Literal["started", "api_retry"]
    attempt: int | None = None
    max_retries: int | None = None
    retry_delay_ms: float | None = None
    error_status: int | None = None

ControlResponse

Bases: TypedDict

Control response.

Source code in src/clawd_code_sdk/models/control.py
class ControlResponse(TypedDict):
    """Control response."""

    subtype: Literal["success"]
    request_id: str
    response: dict[str, Any] | None

ConversationResetMessage

Bases: BaseMessage

Emitted when the CLI starts a new conversation within the same session.

E.g. after /clear, exiting plan mode into a fresh context, or onboarding.

Source code in src/clawd_code_sdk/models/messages.py
class ConversationResetMessage(BaseMessage):
    """Emitted when the CLI starts a new conversation within the same session.

    E.g. after /clear, exiting plan mode into a fresh context, or onboarding.
    """

    type: Literal["conversation_reset"] = "conversation_reset"
    session_id: str
    new_conversation_id: str
    trigger: Literal["clear", "plan_mode_exit", "fresh_session", "onboarding"] | None = None
    user_message_uuid: str | None = None
    timestamp: str | None = None

CwdChangedHookInput

Bases: BaseHookInput

Input data for CwdChanged hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class CwdChangedHookInput(BaseHookInput):
    """Input data for CwdChanged hook events."""

    hook_event_name: Literal["CwdChanged"]
    old_cwd: str
    new_cwd: str

CwdChangedHookSpecificOutput

Bases: TypedDict

Hook-specific output for CwdChanged events.

Source code in src/clawd_code_sdk/models/hooks.py
class CwdChangedHookSpecificOutput(TypedDict):
    """Hook-specific output for CwdChanged events."""

    hookEventName: Literal["CwdChanged"]
    watchPaths: NotRequired[list[str]]

DirectoryAddedHookInput

Bases: BaseHookInput

Input data for DirectoryAdded hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class DirectoryAddedHookInput(BaseHookInput):
    """Input data for DirectoryAdded hook events."""

    hook_event_name: Literal["DirectoryAdded"]
    directory: str
    source: Literal["slash_command", "register_repo_root"]

DocumentBlock

Bases: BaseContentBlock

Document content block (e.g. an attached PDF) in a user message.

Source code in src/clawd_code_sdk/models/content_blocks.py
class DocumentBlock(BaseContentBlock):
    """Document content block (e.g. an attached PDF) in a user message."""

    type: Literal["document"] = "document"
    source: DocumentSource
    title: str | None = None
    context: str | None = None
    citations: dict[str, Any] | None = None

EditOutput

Bases: TypedDict

tool_use_result for the Edit tool.

Source code in src/clawd_code_sdk/models/output_types.py
class EditOutput(TypedDict):
    """``tool_use_result`` for the Edit tool."""

    filePath: str
    oldString: str
    newString: str
    originalFile: str | None
    structuredPatch: list[StructuredPatchHunk]
    userModified: bool
    replaceAll: bool
    gitDiff: NotRequired[GitDiff]
    staged: NotRequired[bool]
    """Whether the edit was staged instead of written."""

staged instance-attribute

staged: NotRequired[bool]

Whether the edit was staged instead of written.

ElicitationCompleteMessage

Bases: BaseSystemMessage

System message emitted when an MCP elicitation completes.

Source code in src/clawd_code_sdk/models/system_messages.py
class ElicitationCompleteMessage(BaseSystemMessage):
    """System message emitted when an MCP elicitation completes."""

    subtype: Literal["elicitation_complete"] = "elicitation_complete"
    mcp_server_name: str
    elicitation_id: str

ElicitationHookInput

Bases: BaseHookInput

Input data for Elicitation hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class ElicitationHookInput(BaseHookInput):
    """Input data for Elicitation hook events."""

    hook_event_name: Literal["Elicitation"]
    mcp_server_name: str
    message: str
    mode: NotRequired[ElicitationMode]
    url: NotRequired[str]
    elicitation_id: NotRequired[str]
    requested_schema: NotRequired[dict[str, Any]]

ElicitationHookSpecificOutput

Bases: TypedDict

Hook-specific output for Elicitation events.

Source code in src/clawd_code_sdk/models/hooks.py
class ElicitationHookSpecificOutput(TypedDict):
    """Hook-specific output for Elicitation events."""

    hookEventName: Literal["Elicitation"]
    action: NotRequired[ElicitationAction]
    content: NotRequired[dict[str, Any]]

ElicitationResultHookInput

Bases: BaseHookInput

Input data for ElicitationResult hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class ElicitationResultHookInput(BaseHookInput):
    """Input data for ElicitationResult hook events."""

    hook_event_name: Literal["ElicitationResult"]
    mcp_server_name: str
    elicitation_id: NotRequired[str]
    mode: NotRequired[ElicitationMode]
    action: ElicitationAction
    content: NotRequired[dict[str, Any]]

ElicitationResultHookSpecificOutput

Bases: TypedDict

Hook-specific output for ElicitationResult events.

Source code in src/clawd_code_sdk/models/hooks.py
class ElicitationResultHookSpecificOutput(TypedDict):
    """Hook-specific output for ElicitationResult events."""

    hookEventName: Literal["ElicitationResult"]
    action: NotRequired[ElicitationAction]
    content: NotRequired[dict[str, Any]]

EnterPlanModeInput

Bases: TypedDict

Input for the EnterPlanMode tool. Enters planning mode.

Not part of the official SDK ToolInputSchemas as of SDK v0.2.62. Shape derived from empirical testing.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class EnterPlanModeInput(TypedDict):
    """Input for the EnterPlanMode tool. Enters planning mode.

    Not part of the official SDK ToolInputSchemas as of SDK v0.2.62.
    Shape derived from empirical testing.
    """

EnterPlanModeOutput

Bases: TypedDict

tool_use_result for the EnterPlanMode tool.

Not part of the official SDK ToolOutputSchemas as of SDK v0.2.62. Shape derived from empirical testing.

Source code in src/clawd_code_sdk/models/output_types.py
class EnterPlanModeOutput(TypedDict):
    """``tool_use_result`` for the EnterPlanMode tool.

    Not part of the official SDK ToolOutputSchemas as of SDK v0.2.62.
    Shape derived from empirical testing.
    """

    message: str
    """A message indicating that plan mode was entered."""

message instance-attribute

message: str

A message indicating that plan mode was entered.

EnterWorktreeOutput

Bases: TypedDict

tool_use_result for the EnterWorktree tool.

Source code in src/clawd_code_sdk/models/output_types.py
class EnterWorktreeOutput(TypedDict):
    """``tool_use_result`` for the EnterWorktree tool."""

    worktreePath: str
    """The path to the worktree."""
    worktreeBranch: NotRequired[str]
    """The branch of the worktree."""
    message: str
    """A message indicating the result of the operation."""

message instance-attribute

message: str

A message indicating the result of the operation.

worktreeBranch instance-attribute

worktreeBranch: NotRequired[str]

The branch of the worktree.

worktreePath instance-attribute

worktreePath: str

The path to the worktree.

ExitPlanModeInput

Bases: TypedDict

Input for the ExitPlanMode tool. Exits planning mode for user approval.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class ExitPlanModeInput(TypedDict):
    """Input for the ExitPlanMode tool. Exits planning mode for user approval."""

    plan: str
    """The plan to run by the user for approval."""

plan instance-attribute

plan: str

The plan to run by the user for approval.

ExitPlanModeOutput

Bases: TypedDict

tool_use_result for the ExitPlanMode tool.

Source code in src/clawd_code_sdk/models/output_types.py
class ExitPlanModeOutput(TypedDict):
    """``tool_use_result`` for the ExitPlanMode tool."""

    plan: str | None
    """The plan that was presented to the user."""
    isAgent: bool
    filePath: NotRequired[str]
    """The file path where the plan was saved."""
    hasTaskTool: NotRequired[bool]
    """Whether the Task tool is available in the current context."""
    planWasEdited: NotRequired[bool]
    """Whether the plan was edited by the user."""
    awaitingLeaderApproval: NotRequired[bool]
    """When true, the teammate has sent a plan approval request to the team leader."""
    requestId: NotRequired[str]
    """Unique identifier for the plan approval request."""

awaitingLeaderApproval instance-attribute

awaitingLeaderApproval: NotRequired[bool]

When true, the teammate has sent a plan approval request to the team leader.

filePath instance-attribute

filePath: NotRequired[str]

The file path where the plan was saved.

hasTaskTool instance-attribute

hasTaskTool: NotRequired[bool]

Whether the Task tool is available in the current context.

plan instance-attribute

plan: str | None

The plan that was presented to the user.

planWasEdited instance-attribute

planWasEdited: NotRequired[bool]

Whether the plan was edited by the user.

requestId instance-attribute

requestId: NotRequired[str]

Unique identifier for the plan approval request.

ExitWorktreeInput

Bases: TypedDict

Input for the ExitWorktree tool.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class ExitWorktreeInput(TypedDict):
    """Input for the ExitWorktree tool."""

    action: Literal["keep", "remove"]
    """'keep' leaves the worktree and branch on disk; 'remove' deletes both."""
    discard_changes: NotRequired[bool]
    """Required true when action is 'remove' and worktree has uncommitted files / unmerged commits.

    The tool will refuse and list them otherwise."""

action instance-attribute

action: Literal['keep', 'remove']

'keep' leaves the worktree and branch on disk; 'remove' deletes both.

discard_changes instance-attribute

discard_changes: NotRequired[bool]

Required true when action is 'remove' and worktree has uncommitted files / unmerged commits.

The tool will refuse and list them otherwise.

ExitWorktreeOutput

Bases: TypedDict

tool_use_result for the ExitWorktree tool.

Source code in src/clawd_code_sdk/models/output_types.py
class ExitWorktreeOutput(TypedDict):
    """``tool_use_result`` for the ExitWorktree tool."""

    action: Literal["keep", "remove"]
    """The action that was taken."""
    originalCwd: str
    """The original working directory before the worktree was entered."""
    worktreePath: str
    """The path to the worktree."""
    worktreeBranch: NotRequired[str]
    """The branch of the worktree."""
    tmuxSessionName: NotRequired[str]
    """The tmux session name if applicable."""
    discardedFiles: NotRequired[int]
    """Number of files discarded."""
    discardedCommits: NotRequired[int]
    """Number of commits discarded."""
    message: str
    """A message indicating the result of the operation."""

action instance-attribute

action: Literal['keep', 'remove']

The action that was taken.

discardedCommits instance-attribute

discardedCommits: NotRequired[int]

Number of commits discarded.

discardedFiles instance-attribute

discardedFiles: NotRequired[int]

Number of files discarded.

message instance-attribute

message: str

A message indicating the result of the operation.

originalCwd instance-attribute

originalCwd: str

The original working directory before the worktree was entered.

tmuxSessionName instance-attribute

tmuxSessionName: NotRequired[str]

The tmux session name if applicable.

worktreeBranch instance-attribute

worktreeBranch: NotRequired[str]

The branch of the worktree.

worktreePath instance-attribute

worktreePath: str

The path to the worktree.

FileChangedHookInput

Bases: BaseHookInput

Input data for FileChanged hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class FileChangedHookInput(BaseHookInput):
    """Input data for FileChanged hook events."""

    hook_event_name: Literal["FileChanged"]
    file_path: str
    event: Literal["change", "add", "unlink"]

FileChangedHookSpecificOutput

Bases: TypedDict

Hook-specific output for FileChanged events.

Source code in src/clawd_code_sdk/models/hooks.py
class FileChangedHookSpecificOutput(TypedDict):
    """Hook-specific output for FileChanged events."""

    hookEventName: Literal["FileChanged"]
    watchPaths: NotRequired[list[str]]

FileDocumentSource

Bases: BaseContentBlock

Document uploaded through the Files API.

Source code in src/clawd_code_sdk/models/content_blocks.py
class FileDocumentSource(BaseContentBlock):
    """Document uploaded through the Files API."""

    type: Literal["file"] = "file"
    file_id: str

FileEditInput

Bases: TypedDict

Input for the Edit tool. Performs exact string replacements in files.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class FileEditInput(TypedDict):
    """Input for the Edit tool. Performs exact string replacements in files."""

    file_path: str
    """The absolute path to the file to modify."""
    old_string: str
    """The text to replace."""
    new_string: str
    """The text to replace it with (must be different from old_string)."""
    replace_all: NotRequired[bool]
    """Replace all occurrences of old_string (default false)."""

file_path instance-attribute

file_path: str

The absolute path to the file to modify.

new_string instance-attribute

new_string: str

The text to replace it with (must be different from old_string).

old_string instance-attribute

old_string: str

The text to replace.

replace_all instance-attribute

replace_all: NotRequired[bool]

Replace all occurrences of old_string (default false).

FileReadInput

Bases: TypedDict

Input for the Read tool. Reads files including text, images, PDFs, and notebooks.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class FileReadInput(TypedDict):
    """Input for the Read tool. Reads files including text, images, PDFs, and notebooks."""

    file_path: str
    """The absolute path to the file to read."""
    offset: NotRequired[int]
    """The line number to start reading from.

    Only provide if the file is too large to read at once."""
    limit: NotRequired[int]
    """The number of lines to read. Only provide if the file is too large to read at once"""
    pages: NotRequired[str]
    """Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files.

    Maximum 20 pages per request."""
    allow_large: NotRequired[bool]
    """Read a text file (or line range) that is over the usual size limits."""

allow_large instance-attribute

allow_large: NotRequired[bool]

Read a text file (or line range) that is over the usual size limits.

file_path instance-attribute

file_path: str

The absolute path to the file to read.

limit instance-attribute

limit: NotRequired[int]

The number of lines to read. Only provide if the file is too large to read at once

offset instance-attribute

offset: NotRequired[int]

The line number to start reading from.

Only provide if the file is too large to read at once.

pages instance-attribute

pages: NotRequired[str]

Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files.

Maximum 20 pages per request.

FileWriteInput

Bases: TypedDict

Input for the Write tool. Writes a file to the local filesystem.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class FileWriteInput(TypedDict):
    """Input for the Write tool. Writes a file to the local filesystem."""

    file_path: str
    """The absolute path to the file to write."""
    content: str
    """The content to write to the file."""

content instance-attribute

content: str

The content to write to the file.

file_path instance-attribute

file_path: str

The absolute path to the file to write.

FilesPersistedSystemMessage

Bases: BaseSystemMessage

System message emitted when files have been persisted.

Source code in src/clawd_code_sdk/models/system_messages.py
class FilesPersistedSystemMessage(BaseSystemMessage):
    """System message emitted when files have been persisted."""

    subtype: Literal["files_persisted"] = "files_persisted"
    files: list[FilePersistedEntry]
    failed: list[FilePersistedFailure]
    processed_at: str

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.

GitDiff

Bases: TypedDict

Git diff information for a file change.

Source code in src/clawd_code_sdk/models/output_types.py
class GitDiff(TypedDict):
    """Git diff information for a file change."""

    filename: str
    status: Literal["modified", "added"]
    additions: int
    deletions: int
    changes: int
    patch: str

GlobInput

Bases: TypedDict

Input for the Glob tool. Fast file pattern matching.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class GlobInput(TypedDict):
    """Input for the Glob tool. Fast file pattern matching."""

    pattern: str
    """The glob pattern to match files against."""
    path: NotRequired[str]
    """The directory to search in (defaults to cwd)."""

path instance-attribute

path: NotRequired[str]

The directory to search in (defaults to cwd).

pattern instance-attribute

pattern: str

The glob pattern to match files against.

GlobOutput

Bases: TypedDict

tool_use_result for the Glob tool.

Source code in src/clawd_code_sdk/models/output_types.py
class GlobOutput(TypedDict):
    """``tool_use_result`` for the Glob tool."""

    durationMs: int
    numFiles: int
    filenames: list[str]
    truncated: bool
    """Whether results were truncated (limited to 100 files)."""
    totalMatches: NotRequired[int]
    """Total matches before truncation (a lower bound when countIsComplete is false)."""
    countIsComplete: NotRequired[bool]
    """Whether totalMatches is exact."""
    timedOut: NotRequired[bool]
    """Whether the search timed out (results may be partial)."""

countIsComplete instance-attribute

countIsComplete: NotRequired[bool]

Whether totalMatches is exact.

timedOut instance-attribute

timedOut: NotRequired[bool]

Whether the search timed out (results may be partial).

totalMatches instance-attribute

totalMatches: NotRequired[int]

Total matches before truncation (a lower bound when countIsComplete is false).

truncated instance-attribute

truncated: bool

Whether results were truncated (limited to 100 files).

GrepOutput

Bases: TypedDict

tool_use_result for the Grep tool (all modes).

Source code in src/clawd_code_sdk/models/output_types.py
class GrepOutput(TypedDict):
    """``tool_use_result`` for the Grep tool (all modes)."""

    mode: NotRequired[Literal["content", "files_with_matches", "count"]]
    numFiles: int
    filenames: list[str]
    content: NotRequired[str]
    """Matching lines (content mode)."""
    numLines: NotRequired[int]
    """Number of matching lines (content mode)."""
    numMatches: NotRequired[int]
    """Number of matches (count mode)."""
    appliedLimit: NotRequired[int]
    """The head_limit that was applied."""
    appliedOffset: NotRequired[int]
    """The offset that was applied."""
    totalFiles: NotRequired[int]
    """Total matching files before pagination."""
    totalLines: NotRequired[int]
    """Total matching lines before pagination."""
    timedOut: NotRequired[bool]
    """Whether the search timed out (results may be partial)."""

appliedLimit instance-attribute

appliedLimit: NotRequired[int]

The head_limit that was applied.

appliedOffset instance-attribute

appliedOffset: NotRequired[int]

The offset that was applied.

content instance-attribute

content: NotRequired[str]

Matching lines (content mode).

numLines instance-attribute

numLines: NotRequired[int]

Number of matching lines (content mode).

numMatches instance-attribute

numMatches: NotRequired[int]

Number of matches (count mode).

timedOut instance-attribute

timedOut: NotRequired[bool]

Whether the search timed out (results may be partial).

totalFiles instance-attribute

totalFiles: NotRequired[int]

Total matching files before pagination.

totalLines instance-attribute

totalLines: NotRequired[int]

Total matching lines before pagination.

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]

HookProgressSystemMessage

Bases: BaseSystemMessage

Progress update from a running hook.

Source code in src/clawd_code_sdk/models/system_messages.py
class HookProgressSystemMessage(BaseSystemMessage):
    """Progress update from a running hook."""

    subtype: Literal["hook_progress"] = "hook_progress"
    hook_id: str
    hook_name: str
    hook_event: str
    stdout: str
    stderr: str
    output: str

HookResponseSystemMessage

Bases: BaseSystemMessage

System message emitted when a hook completes.

Source code in src/clawd_code_sdk/models/system_messages.py
class HookResponseSystemMessage(BaseSystemMessage):
    """System message emitted when a hook completes."""

    subtype: Literal["hook_response"] = "hook_response"
    hook_id: str
    hook_name: str
    hook_event: str
    outcome: Outcome
    exit_code: int | None = None
    stderr: str
    stdout: str
    output: str

HookStartedSystemMessage

Bases: BaseSystemMessage

System message emitted when a hook starts.

Source code in src/clawd_code_sdk/models/system_messages.py
class HookStartedSystemMessage(BaseSystemMessage):
    """System message emitted when a hook starts."""

    subtype: Literal["hook_started"] = "hook_started"
    hook_id: str
    hook_name: str
    hook_event: str

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

InformationalSystemMessage

Bases: BaseSystemMessage

Informational text from the CLI (notices, suggestions, warnings).

Source code in src/clawd_code_sdk/models/system_messages.py
class InformationalSystemMessage(BaseSystemMessage):
    """Informational text from the CLI (notices, suggestions, warnings)."""

    subtype: Literal["informational"] = "informational"
    content: str
    level: Literal["info", "notice", "suggestion", "warning"]
    tool_use_id: str | None = None
    prevent_continuation: bool | None = None
    tag: str | None = None

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+).

InstructionsLoadedHookInput

Bases: BaseHookInput

Input data for InstructionsLoaded hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class InstructionsLoadedHookInput(BaseHookInput):
    """Input data for InstructionsLoaded hook events."""

    hook_event_name: Literal["InstructionsLoaded"]
    file_path: str
    memory_type: Literal["User", "Project", "Local", "Managed"]
    load_reason: LoadReason
    globs: NotRequired[list[str]]
    trigger_file_path: NotRequired[str]
    parent_file_path: NotRequired[str]

JSONRPCError

Bases: TypedDict

A JSON-RPC error object.

Source code in src/clawd_code_sdk/models/mcp.py
class JSONRPCError(TypedDict):
    """A JSON-RPC error object."""

    code: int
    message: str
    data: NotRequired[object]

JSONRPCErrorResponse

Bases: TypedDict

A response to a request that indicates an error occurred.

Source code in src/clawd_code_sdk/models/mcp.py
class JSONRPCErrorResponse(TypedDict):
    """A response to a request that indicates an error occurred."""

    jsonrpc: str
    id: NotRequired[RequestId]
    error: JSONRPCError

JSONRPCNotification

Bases: TypedDict

A JSON-RPC notification which does not expect a response.

Source code in src/clawd_code_sdk/models/mcp.py
class JSONRPCNotification(TypedDict):
    """A JSON-RPC notification which does not expect a response."""

    jsonrpc: str
    method: str
    params: NotRequired[dict[str, Any]]

JSONRPCRequest

Bases: TypedDict

A JSON-RPC request that expects a response.

Source code in src/clawd_code_sdk/models/mcp.py
class JSONRPCRequest(TypedDict):
    """A JSON-RPC request that expects a response."""

    jsonrpc: str
    id: RequestId
    method: str
    params: NotRequired[dict[str, Any]]

JSONRPCResultResponse

Bases: TypedDict

A successful (non-error) response to a request.

Source code in src/clawd_code_sdk/models/mcp.py
class JSONRPCResultResponse(TypedDict):
    """A successful (non-error) response to a request."""

    jsonrpc: str
    id: RequestId
    result: dict[str, Any]

KillShellInput

Bases: TypedDict

Input for the KillBash tool. Kills a running background bash shell.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class KillShellInput(TypedDict):
    """Input for the KillBash tool. Kills a running background bash shell."""

    shell_id: str
    """The ID of the background shell to kill."""

shell_id instance-attribute

shell_id: str

The ID of the background shell to kill.

KillShellOutput

Bases: TypedDict

tool_use_result for the KillBash tool.

Not part of the official SDK ToolOutputSchemas as of SDK v0.2.62. Shape derived from: https://github.com/kzahel/yepanywhere/blob/main/packages/shared/src/claude-sdk-schema/tool/ToolResultSchemas.ts

Source code in src/clawd_code_sdk/models/output_types.py
class KillShellOutput(TypedDict):
    """``tool_use_result`` for the KillBash tool.

    Not part of the official SDK ToolOutputSchemas as of SDK v0.2.62.
    Shape derived from: https://github.com/kzahel/yepanywhere/blob/main/packages/shared/src/claude-sdk-schema/tool/ToolResultSchemas.ts
    """

    message: NotRequired[str]
    """Status message."""
    shell_id: NotRequired[str]
    """ID of the shell that was killed."""

message instance-attribute

message: NotRequired[str]

Status message.

shell_id instance-attribute

shell_id: NotRequired[str]

ID of the shell that was killed.

ListMcpResourcesInput

Bases: TypedDict

Input for the ListMcpResources tool. Lists available MCP resources.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class ListMcpResourcesInput(TypedDict):
    """Input for the ListMcpResources tool. Lists available MCP resources."""

    server: NotRequired[str]
    """Optional server name to filter resources by."""

server instance-attribute

server: NotRequired[str]

Optional server name to filter resources by.

LocalCommandOutputMessage

Bases: BaseSystemMessage

Output from a local slash command (e.g. /voice, /cost).

Displayed as assistant-style text in the transcript.

Source code in src/clawd_code_sdk/models/system_messages.py
class LocalCommandOutputMessage(BaseSystemMessage):
    """Output from a local slash command (e.g. /voice, /cost).

    Displayed as assistant-style text in the transcript.
    """

    subtype: Literal["local_command_output"] = "local_command_output"
    content: str

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.

McpClaudeAIProxyServerConfig dataclass

MCP Claude AI proxy server configuration.

Source code in src/clawd_code_sdk/models/mcp.py
@dataclass(kw_only=True)
class McpClaudeAIProxyServerConfig:
    """MCP Claude AI proxy server configuration."""

    type: Literal["claudeai-proxy"] = "claudeai-proxy"
    url: str
    id: str
    timeout: float | None = None

McpHttpServerConfig dataclass

Bases: BaseMcpServerConfig

MCP HTTP server configuration.

Source code in src/clawd_code_sdk/models/mcp.py
@dataclass(kw_only=True)
class McpHttpServerConfig(BaseMcpServerConfig):
    """MCP HTTP server configuration."""

    type: Literal["http"] = "http"
    url: str
    headers: dict[str, str] = field(default_factory=dict)
    tools: list[McpServerToolPolicy] | None = field(default=None)

McpResourceContents

Bases: BaseModel

A single resource content entry.

Source code in src/clawd_code_sdk/models/control.py
class McpResourceContents(BaseModel):
    """A single resource content entry."""

    model_config = ConfigDict(populate_by_name=True)

    uri: str
    mime_type: str | None = Field(default=None, alias="mimeType")
    text: str | None = None
    blob: str | None = None
    meta: dict[str, Any] | None = Field(default=None, alias="_meta")

McpResourceEntry

Bases: TypedDict

A single MCP resource entry.

Source code in src/clawd_code_sdk/models/output_types.py
class McpResourceEntry(TypedDict):
    """A single MCP resource entry."""

    uri: str
    """Resource URI."""
    name: str
    """Resource name."""
    description: NotRequired[str]
    """Resource description."""
    mimeType: NotRequired[str]
    """Resource MIME type."""
    server: str
    """Server providing this resource."""

description instance-attribute

description: NotRequired[str]

Resource description.

mimeType instance-attribute

mimeType: NotRequired[str]

Resource MIME type.

name instance-attribute

name: str

Resource name.

server instance-attribute

server: str

Server providing this resource.

uri instance-attribute

uri: str

Resource URI.

McpSSEServerConfig dataclass

Bases: BaseMcpServerConfig

MCP SSE server configuration.

Source code in src/clawd_code_sdk/models/mcp.py
@dataclass(kw_only=True)
class McpSSEServerConfig(BaseMcpServerConfig):
    """MCP SSE server configuration."""

    type: Literal["sse"] = "sse"
    url: str
    headers: dict[str, str] = field(default_factory=dict)
    tools: list[McpServerToolPolicy] | None = field(default=None)

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)

McpServerProvenance

Bases: TypedDict

Which MCP server (and config source) a tool call belongs to.

Source code in src/clawd_code_sdk/models/hooks.py
class McpServerProvenance(TypedDict):
    """Which MCP server (and config source) a tool call belongs to."""

    name: str
    source: str

McpServerStatus

Bases: BaseModel

MCP server status.

Source code in src/clawd_code_sdk/models/system_messages.py
class McpServerStatus(BaseModel):
    """MCP server status."""

    name: str
    status: McpConnectionStatus
    source: str | None = None

McpServerStatusEntry

Bases: ClaudeCodeBaseModel

Status information for a single MCP server.

Source code in src/clawd_code_sdk/models/mcp.py
class McpServerStatusEntry(ClaudeCodeBaseModel):
    """Status information for a single MCP server."""

    name: str
    status: McpConnectionStatus
    server_info: McpServerVersionInfo | None = None
    error: str | None = None
    config: McpServerStatusConfig | None = None
    scope: Literal["project", "user", "local", "claudeai", "managed"] | str | None = None  # noqa: PYI051
    tools: list[McpToolStatus] = Field(default_factory=list)

McpServerVersionInfo

Bases: ClaudeCodeBaseModel

Server version information returned in MCP status.

Source code in src/clawd_code_sdk/models/mcp.py
class McpServerVersionInfo(ClaudeCodeBaseModel):
    """Server version information returned in MCP status."""

    name: str
    version: str

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)

McpStatusResponse

Bases: ClaudeCodeBaseModel

Response from get_mcp_status() containing all MCP server statuses.

Source code in src/clawd_code_sdk/models/mcp.py
class McpStatusResponse(ClaudeCodeBaseModel):
    """Response from get_mcp_status() containing all MCP server statuses."""

    mcp_servers: list[McpServerStatusEntry] = Field(default_factory=list)

McpStdioServerConfig dataclass

Bases: BaseMcpServerConfig

MCP stdio server configuration.

Source code in src/clawd_code_sdk/models/mcp.py
@dataclass(kw_only=True)
class McpStdioServerConfig(BaseMcpServerConfig):
    """MCP stdio server configuration."""

    type: Literal["stdio"] = "stdio"
    command: str
    args: list[str] = field(default_factory=list)
    env: dict[str, str] = field(default_factory=dict)

McpToolStatus

Bases: ClaudeCodeBaseModel

Status information for a single MCP tool.

Source code in src/clawd_code_sdk/models/mcp.py
class McpToolStatus(ClaudeCodeBaseModel):
    """Status information for a single MCP tool."""

    name: str
    description: str | None = None
    annotations: ToolAnnotations = Field(default_factory=ToolAnnotations)

MemoryRecallSystemMessage

Bases: BaseSystemMessage

Emitted when the memory recall supervisor surfaces relevant memories into the turn.

Mirrors the CLI relevant_memories attachment so SDK renderers can show "Recalled from memory" inline.

Source code in src/clawd_code_sdk/models/system_messages.py
class MemoryRecallSystemMessage(BaseSystemMessage):
    """Emitted when the memory recall supervisor surfaces relevant memories into the turn.

    Mirrors the CLI relevant_memories attachment so SDK renderers can show
    "Recalled from memory" inline.
    """

    subtype: Literal["memory_recall"] = "memory_recall"
    mode: Literal["select", "synthesize"]
    """Mode of memory recall."""
    memories: list[Memory]
    """List of memory objects."""

memories instance-attribute

memories: list[Memory]

List of memory objects.

mode instance-attribute

mode: Literal['select', 'synthesize']

Mode of memory recall.

MessageDisplayHookInput

Bases: BaseHookInput

Input data for MessageDisplay hook events (assistant text being displayed).

Source code in src/clawd_code_sdk/models/hooks.py
class MessageDisplayHookInput(BaseHookInput):
    """Input data for MessageDisplay hook events (assistant text being displayed)."""

    hook_event_name: Literal["MessageDisplay"]
    turn_id: str
    message_id: str
    index: int
    final: bool
    delta: str

MessageDisplayHookSpecificOutput

Bases: TypedDict

Hook-specific output for MessageDisplay events.

Source code in src/clawd_code_sdk/models/hooks.py
class MessageDisplayHookSpecificOutput(TypedDict):
    """Hook-specific output for MessageDisplay events."""

    hookEventName: Literal["MessageDisplay"]
    displayContent: NotRequired[str]
    """Replacement text to display instead of the delta."""

displayContent instance-attribute

displayContent: NotRequired[str]

Replacement text to display instead of the delta.

MessageParam

Bases: ClaudeCodeBaseModel

User message payload wrapping content blocks.

Only used for user-role messages; assistant messages use :class:AssistantMessageContent.

Source code in src/clawd_code_sdk/models/content_blocks.py
class MessageParam(ClaudeCodeBaseModel):
    """User message payload wrapping content blocks.

    Only used for user-role messages; assistant messages use
    :class:`AssistantMessageContent`.
    """

    content: Sequence[UserContentBlock] | str
    role: Literal["user"] = "user"
    model_config = ConfigDict(extra="allow")

MirrorErrorSystemMessage

Bases: BaseSystemMessage

Emitted when SessionStore.append() rejects or times out for a transcript-mirror batch.

The batch is dropped (at-most-once delivery); this surfaces the failure so consumers are not silent on data loss.

Source code in src/clawd_code_sdk/models/system_messages.py
class MirrorErrorSystemMessage(BaseSystemMessage):
    """Emitted when SessionStore.append() rejects or times out for a transcript-mirror batch.

    The batch is dropped (at-most-once delivery);
    this surfaces the failure so consumers are not silent on data loss.
    """

    subtype: Literal["mirror_error"] = "mirror_error"
    error: str
    key: SessionKey

ModelRefusalFallbackMessage

Bases: BaseSystemMessage

Emitted when a model refusal triggered a switch to a fallback model.

Source code in src/clawd_code_sdk/models/system_messages.py
class ModelRefusalFallbackMessage(BaseSystemMessage):
    """Emitted when a model refusal triggered a switch to a fallback model."""

    subtype: Literal["model_refusal_fallback"] = "model_refusal_fallback"
    trigger: Literal["refusal"]
    direction: Literal["retry", "revert", "sticky"]
    scope: Literal["session", "local"] | None = None
    original_model: str
    fallback_model: str
    request_id: str | None
    api_refusal_category: str | None = None
    api_refusal_explanation: str | None = None
    retracted_message_uuids: list[str] | None = None
    refused_user_message_uuid: str | None = None
    content: str

ModelRefusalNoFallbackMessage

Bases: BaseSystemMessage

Emitted when the model refused and no fallback model is available.

Source code in src/clawd_code_sdk/models/system_messages.py
class ModelRefusalNoFallbackMessage(BaseSystemMessage):
    """Emitted when the model refused and no fallback model is available."""

    subtype: Literal["model_refusal_no_fallback"] = "model_refusal_no_fallback"
    original_model: str
    request_id: str | None
    api_refusal_category: str | None = None
    api_refusal_explanation: str | None = None
    refused_user_message_uuid: str | None = None
    content: str

ModelScopedUsageWindow

Bases: UsageWindow

Per-model weekly window.

Source code in src/clawd_code_sdk/models/context_usage.py
class ModelScopedUsageWindow(UsageWindow):
    """Per-model weekly window."""

    display_name: str

ModelUsage

Bases: ClaudeCodeBaseModel

Cumulative token usage per model, accumulated across the entire session.

Source code in src/clawd_code_sdk/models/usage.py
class ModelUsage(ClaudeCodeBaseModel):
    """Cumulative token usage per model, accumulated across the entire session."""

    input_tokens: int
    output_tokens: int
    thinking_tokens: int | None = None
    cache_read_input_tokens: int
    cache_creation_input_tokens: int
    cache_creation_ephemeral5m_input_tokens: int | None = Field(
        default=None, alias="cacheCreationEphemeral5mInputTokens"
    )
    cache_creation_ephemeral1h_input_tokens: int | None = Field(
        default=None, alias="cacheCreationEphemeral1hInputTokens"
    )
    web_search_requests: int
    cost_usd: float = Field(default=..., alias="costUSD")
    context_window: int
    max_output_tokens: int
    canonical_model: str | None = None
    provider: str | None = None
    cost_basis: Literal["list", "managed", "unknown"] | None = None

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.

NotebookEditInput

Bases: TypedDict

Input for the NotebookEdit tool. Edits cells in Jupyter notebook files.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class NotebookEditInput(TypedDict):
    """Input for the NotebookEdit tool. Edits cells in Jupyter notebook files."""

    notebook_path: str
    """The absolute path to the Jupyter notebook file."""
    new_source: str
    """The new source for the cell."""
    cell_id: NotRequired[str]
    """The ID of the cell to edit."""
    cell_type: NotRequired[Literal["code", "markdown"]]
    """The type of the cell (code or markdown)."""
    edit_mode: NotRequired[Literal["replace", "insert", "delete"]]
    """The type of edit (replace, insert, delete)."""

cell_id instance-attribute

cell_id: NotRequired[str]

The ID of the cell to edit.

cell_type instance-attribute

cell_type: NotRequired[Literal['code', 'markdown']]

The type of the cell (code or markdown).

edit_mode instance-attribute

edit_mode: NotRequired[Literal['replace', 'insert', 'delete']]

The type of edit (replace, insert, delete).

new_source instance-attribute

new_source: str

The new source for the cell.

notebook_path instance-attribute

notebook_path: str

The absolute path to the Jupyter notebook file.

NotebookEditOutput

Bases: TypedDict

tool_use_result for the NotebookEdit tool.

Source code in src/clawd_code_sdk/models/output_types.py
class NotebookEditOutput(TypedDict):
    """``tool_use_result`` for the NotebookEdit tool."""

    new_source: str
    cell_id: NotRequired[str]
    cell_type: Literal["code", "markdown"]
    language: str
    edit_mode: str
    error: NotRequired[str]
    notebook_path: str
    original_file: str
    """The original notebook content before modification."""
    updated_file: str
    """The updated notebook content after modification."""
    old_source: NotRequired[str]
    """The original source of the cell before the edit."""

old_source instance-attribute

old_source: NotRequired[str]

The original source of the cell before the edit.

original_file instance-attribute

original_file: str

The original notebook content before modification.

updated_file instance-attribute

updated_file: str

The updated notebook content after modification.

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]

NotificationSystemMessage

Bases: BaseSystemMessage

Loop-side text notification.

Mirrors the interactive REPL notification queue (key/priority/timeout). JSX notifications are not emitted on this channel.

Source code in src/clawd_code_sdk/models/system_messages.py
class NotificationSystemMessage(BaseSystemMessage):
    """Loop-side text notification.

    Mirrors the interactive REPL notification queue (key/priority/timeout).
    JSX notifications are not emitted on this channel.
    """

    subtype: Literal["notification"] = "notification"
    key: str
    text: str
    priority: Literal["low", "medium", "high", "immediate"]
    color: str | None = None
    timeout_ms: int | None = None

PermissionDeniedHookInput

Bases: BaseHookInput

Input data for PermissionDenied hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class PermissionDeniedHookInput(BaseHookInput):
    """Input data for PermissionDenied hook events."""

    hook_event_name: Literal["PermissionDenied"]
    tool_name: str
    tool_input: Any
    tool_use_id: str
    reason: str
    mcp_server: NotRequired[McpServerProvenance]

PermissionDeniedHookSpecificOutput

Bases: TypedDict

Hook-specific output for PermissionDenied events.

Source code in src/clawd_code_sdk/models/hooks.py
class PermissionDeniedHookSpecificOutput(TypedDict):
    """Hook-specific output for PermissionDenied events."""

    hookEventName: Literal["PermissionDenied"]
    retry: NotRequired[bool]

PermissionDeniedSystemMessage

Bases: BaseSystemMessage

Emitted when a tool call was denied by the permission system.

Source code in src/clawd_code_sdk/models/system_messages.py
class PermissionDeniedSystemMessage(BaseSystemMessage):
    """Emitted when a tool call was denied by the permission system."""

    subtype: Literal["permission_denied"] = "permission_denied"
    tool_name: ToolName | str
    tool_use_id: str
    agent_id: str | None = None
    decision_reason_type: str | None = None
    decision_reason: str | None = None
    message: 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

PermissionRuleValue

Bases: ClaudeCodeBaseModel

Permission rule value.

Source code in src/clawd_code_sdk/models/permissions.py
class PermissionRuleValue(ClaudeCodeBaseModel):
    """Permission rule value."""

    tool_name: str
    rule_content: str | 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

PlainTextSource

Bases: BaseContentBlock

Plain text document.

Source code in src/clawd_code_sdk/models/content_blocks.py
class PlainTextSource(BaseContentBlock):
    """Plain text document."""

    type: Literal["text"] = "text"
    media_type: Literal["text/plain"] = "text/plain"
    data: str

PluginInstallSystemMessage

Bases: BaseSystemMessage

System message emitted when a plugin is installed.

Source code in src/clawd_code_sdk/models/system_messages.py
class PluginInstallSystemMessage(BaseSystemMessage):
    """System message emitted when a plugin is installed."""

    subtype: Literal["plugin_install"] = "plugin_install"
    status: Literal["started", "installed", "failed", "completed"]
    name: str | None = None
    error: str | None = None

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

PostModelSwitchHookInput

Bases: BaseHookInput

Input data for PostModelSwitch hook events (after the session model changed).

Source code in src/clawd_code_sdk/models/hooks.py
class PostModelSwitchHookInput(BaseHookInput):
    """Input data for PostModelSwitch hook events (after the session model changed)."""

    hook_event_name: Literal["PostModelSwitch"]
    from_model: str
    to_model: str
    requested_model: str | None
    source: Literal["command", "picker", "sdk", "auto", "resume"]
    context_tokens: int
    prompt_cache_warm: bool
    cache_ttl: ModelSwitchCacheTtl
    estimated_cache_write_usd: float
    pricing: ModelSwitchPricing

PostModelSwitchHookSpecificOutput

Bases: TypedDict

Hook-specific output for PostModelSwitch events.

Source code in src/clawd_code_sdk/models/hooks.py
class PostModelSwitchHookSpecificOutput(TypedDict):
    """Hook-specific output for PostModelSwitch events."""

    hookEventName: Literal["PostModelSwitch"]
    additionalContext: NotRequired[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]

PostToolUseHookSpecificOutput

Bases: TypedDict

Hook-specific output for PostToolUse events.

Source code in src/clawd_code_sdk/models/hooks.py
class PostToolUseHookSpecificOutput(TypedDict):
    """Hook-specific output for PostToolUse events."""

    hookEventName: Literal["PostToolUse"]
    additionalContext: NotRequired[str]
    classifierContext: NotRequired[str]
    updatedToolOutput: NotRequired[Any]
    """Replace the tool output the model sees (any tool)."""
    updatedMCPToolOutput: NotRequired[Any]

updatedToolOutput instance-attribute

updatedToolOutput: NotRequired[Any]

Replace the tool output the model sees (any tool).

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

PreModelSwitchHookInput

Bases: BaseHookInput

Input data for PreModelSwitch hook events (before the session model changes).

Source code in src/clawd_code_sdk/models/hooks.py
class PreModelSwitchHookInput(BaseHookInput):
    """Input data for PreModelSwitch hook events (before the session model changes)."""

    hook_event_name: Literal["PreModelSwitch"]
    from_model: str
    to_model: str
    requested_model: str | None
    source: Literal["command", "picker", "sdk"]
    context_tokens: int
    prompt_cache_warm: bool
    cache_ttl: ModelSwitchCacheTtl
    estimated_cache_write_usd: float
    pricing: ModelSwitchPricing

PreModelSwitchHookSpecificOutput

Bases: TypedDict

Hook-specific output for PreModelSwitch events.

Source code in src/clawd_code_sdk/models/hooks.py
class PreModelSwitchHookSpecificOutput(TypedDict):
    """Hook-specific output for PreModelSwitch events."""

    hookEventName: Literal["PreModelSwitch"]
    permissionDecision: NotRequired[Literal["allow", "deny", "ask"]]
    permissionDecisionReason: NotRequired[str]

PreSkillShellCommandHookInput

Bases: BaseHookInput

Input data for PreSkillShellCommand hook events.

Fires for each inline shell command of a skill or slash command as it loads.

Source code in src/clawd_code_sdk/models/hooks.py
class PreSkillShellCommandHookInput(BaseHookInput):
    """Input data for PreSkillShellCommand hook events.

    Fires for each inline shell command of a skill or slash command as it loads.
    """

    hook_event_name: Literal["PreSkillShellCommand"]
    tool_name: str
    """The shell tool that runs the command: Bash or PowerShell."""
    tool_input: PreSkillShellCommandToolInput
    tool_use_id: str
    """Identifies this command. It names no tool call in the transcript."""
    command_name: str
    """The skill or command whose text holds the shell command."""
    command_source: NotRequired[str]
    invoked_by: Literal["user", "claude", "other"]
    """Who started the load (user: typed or sent by an SDK host, claude: the Skill tool)."""

command_name instance-attribute

command_name: str

The skill or command whose text holds the shell command.

invoked_by instance-attribute

invoked_by: Literal['user', 'claude', 'other']

Who started the load (user: typed or sent by an SDK host, claude: the Skill tool).

tool_name instance-attribute

tool_name: str

The shell tool that runs the command: Bash or PowerShell.

tool_use_id instance-attribute

tool_use_id: str

Identifies this command. It names no tool call in the transcript.

PreSkillShellCommandHookSpecificOutput

Bases: TypedDict

Hook-specific output for PreSkillShellCommand events (refuse or rewrite the command).

Source code in src/clawd_code_sdk/models/hooks.py
class PreSkillShellCommandHookSpecificOutput(TypedDict):
    """Hook-specific output for PreSkillShellCommand events (refuse or rewrite the command)."""

    hookEventName: Literal["PreSkillShellCommand"]
    permissionDecision: NotRequired[HookPermissionDecision]
    permissionDecisionReason: NotRequired[str]
    updatedInput: NotRequired[dict[str, Any]]

PreSkillShellCommandToolInput

Bases: TypedDict

Tool input of a PreSkillShellCommand hook.

Source code in src/clawd_code_sdk/models/hooks.py
class PreSkillShellCommandToolInput(TypedDict):
    """Tool input of a PreSkillShellCommand hook."""

    command: str
    """The command as it would run, with arguments filled in."""

command instance-attribute

command: str

The command as it would run, with arguments filled in.

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]

PreToolUseHookSpecificOutput

Bases: TypedDict

Hook-specific output for PreToolUse events.

Source code in src/clawd_code_sdk/models/hooks.py
class PreToolUseHookSpecificOutput(TypedDict):
    """Hook-specific output for PreToolUse events."""

    hookEventName: Literal["PreToolUse"]
    permissionDecision: NotRequired[HookPermissionDecision]
    permissionDecisionReason: NotRequired[str]
    updatedInput: NotRequired[dict[str, Any]]
    additionalContext: NotRequired[str]

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]

PromptRequest

Bases: TypedDict

Prompt request sent to the SDK consumer.

Source code in src/clawd_code_sdk/models/prompt_requests.py
class PromptRequest(TypedDict):
    """Prompt request sent to the SDK consumer."""

    prompt: str
    """Request ID. Presence of this key marks the line as a prompt request."""
    message: str
    """The prompt message to display to the user."""
    options: list[PromptRequestOption]
    """Available options for the user to choose from."""

message instance-attribute

message: str

The prompt message to display to the user.

options instance-attribute

options: list[PromptRequestOption]

Available options for the user to choose from.

prompt instance-attribute

prompt: str

Request ID. Presence of this key marks the line as a prompt request.

PromptRequestOption

Bases: TypedDict

An option in a prompt request.

Source code in src/clawd_code_sdk/models/prompt_requests.py
class PromptRequestOption(TypedDict):
    """An option in a prompt request."""

    key: str
    """Unique key for this option, returned in the response."""
    label: str
    """Display text for this option."""
    description: NotRequired[str]
    """Optional description shown below the label."""

description instance-attribute

description: NotRequired[str]

Optional description shown below the label.

key instance-attribute

key: str

Unique key for this option, returned in the response.

label instance-attribute

label: str

Display text for this option.

PromptResponse

Bases: TypedDict

Response to a prompt request.

Source code in src/clawd_code_sdk/models/prompt_requests.py
class PromptResponse(TypedDict):
    """Response to a prompt request."""

    prompt_response: str
    """The request ID from the corresponding prompt request."""
    selected: str
    """The key of the selected option."""

prompt_response instance-attribute

prompt_response: str

The request ID from the corresponding prompt request.

selected instance-attribute

selected: str

The key of the selected option.

PromptSuggestionMessage

Bases: BaseMessage

Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.

Source code in src/clawd_code_sdk/models/messages.py
class PromptSuggestionMessage(BaseMessage):
    """Predicted next user prompt, emitted after each turn when promptSuggestions is enabled."""

    type: Literal["prompt_suggestion"] = "prompt_suggestion"
    session_id: str
    suggestion: str

RateLimitInfo

Bases: ClaudeCodeBaseModel

Rate limit information.

Source code in src/clawd_code_sdk/models/messages.py
class RateLimitInfo(ClaudeCodeBaseModel):
    """Rate limit information."""

    status: RateLimitStatus
    resets_at: int | None = None
    rate_limit_type: RateLimitType | None = None
    utilization: float | None = None
    overage_status: RateLimitStatus | None = None
    overage_resets_at: int | None = None
    overage_disabled_reason: OverAgeDisabledReason | None = None
    is_using_overage: bool | None = None
    overage_in_use: bool | None = None
    overage_enabled: bool | None = None
    surpassed_threshold: float | None = None
    limit_scope: Literal["service", "channel", "group_pool"] | None = None
    error_code: Literal["credits_required"] | None = None
    can_user_purchase_credits: bool | None = None
    has_chargeable_saved_payment_method: bool | None = None
    unified_windows: dict[str, Any] | None = None
    """Per-window utilization/status (e.g. ``five_hour``, ``seven_day``); undocumented."""

unified_windows class-attribute instance-attribute

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

Per-window utilization/status (e.g. five_hour, seven_day); undocumented.

RateLimitMessage

Bases: BaseMessage

Rate limit event message.

Source code in src/clawd_code_sdk/models/messages.py
class RateLimitMessage(BaseMessage):
    """Rate limit event message."""

    type: Literal["rate_limit_event"] = "rate_limit_event"
    subtype: Literal["rate_limit"] = "rate_limit"
    session_id: str
    rate_limit_info: RateLimitInfo

ReadFileInfo

Bases: TypedDict

Nested file info inside a Read tool result (text mode).

Source code in src/clawd_code_sdk/models/output_types.py
class ReadFileInfo(TypedDict):
    """Nested file info inside a Read tool result (text mode)."""

    filePath: str
    """The path to the file that was read."""
    content: str
    """The read content of the file."""
    numLines: int
    """The number of lines read."""
    startLine: int
    """The line number where reading started from."""
    totalLines: int
    """The total number of lines in the file."""
    # resultWasTruncated: NotRequired[bool]
    # """Whether the result was truncated due to the maximum token limit."""
    truncatedByTokenCap: NotRequired[bool]
    """True when a whole-file read was auto-paginated because it exceeded the token cap."""

content instance-attribute

content: str

The read content of the file.

filePath instance-attribute

filePath: str

The path to the file that was read.

numLines instance-attribute

numLines: int

The number of lines read.

startLine instance-attribute

startLine: int

The line number where reading started from.

totalLines instance-attribute

totalLines: int

The total number of lines in the file.

truncatedByTokenCap instance-attribute

truncatedByTokenCap: NotRequired[bool]

True when a whole-file read was auto-paginated because it exceeded the token cap.

ReadImageDimensions

Bases: TypedDict

Image dimension info for coordinate mapping.

Source code in src/clawd_code_sdk/models/output_types.py
class ReadImageDimensions(TypedDict):
    """Image dimension info for coordinate mapping."""

    originalWidth: NotRequired[int]
    originalHeight: NotRequired[int]
    displayWidth: NotRequired[int]
    displayHeight: NotRequired[int]

ReadImageFileInfo

Bases: TypedDict

Nested file info for image reads.

Source code in src/clawd_code_sdk/models/output_types.py
class ReadImageFileInfo(TypedDict):
    """Nested file info for image reads."""

    base64: str
    """Base64-encoded image data."""
    type: MimeType
    """The MIME type of the image."""
    originalSize: int
    """Original file size in bytes."""
    dimensions: NotRequired[ReadImageDimensions]

base64 instance-attribute

base64: str

Base64-encoded image data.

originalSize instance-attribute

originalSize: int

Original file size in bytes.

type instance-attribute

type: MimeType

The MIME type of the image.

ReadImageOutput

Bases: TypedDict

tool_use_result for the Read tool (image files).

Source code in src/clawd_code_sdk/models/output_types.py
class ReadImageOutput(TypedDict):
    """``tool_use_result`` for the Read tool (image files)."""

    type: Literal["image"]
    file: ReadImageFileInfo

ReadMcpResourceContentItem

Bases: TypedDict

A single content item from an MCP resource.

Source code in src/clawd_code_sdk/models/output_types.py
class ReadMcpResourceContentItem(TypedDict):
    """A single content item from an MCP resource."""

    uri: str
    """Resource URI."""
    mimeType: NotRequired[str]
    """Content MIME type."""
    text: NotRequired[str]
    """Text content."""

mimeType instance-attribute

mimeType: NotRequired[str]

Content MIME type.

text instance-attribute

text: NotRequired[str]

Text content.

uri instance-attribute

uri: str

Resource URI.

ReadMcpResourceInput

Bases: TypedDict

Input for the ReadMcpResource tool. Reads a specific MCP resource from a server.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class ReadMcpResourceInput(TypedDict):
    """Input for the ReadMcpResource tool. Reads a specific MCP resource from a server."""

    server: str
    """The MCP server name."""
    uri: str
    """The resource URI to read."""

server instance-attribute

server: str

The MCP server name.

uri instance-attribute

uri: str

The resource URI to read.

ReadMcpResourceOutput

Bases: TypedDict

tool_use_result for the ReadMcpResource tool.

Source code in src/clawd_code_sdk/models/output_types.py
class ReadMcpResourceOutput(TypedDict):
    """``tool_use_result`` for the ReadMcpResource tool."""

    contents: list[ReadMcpResourceContentItem]
    """Resource contents."""
    error: NotRequired[str]
    """Error message when the resource could not be read."""

contents instance-attribute

Resource contents.

error instance-attribute

error: NotRequired[str]

Error message when the resource could not be read.

ReadNotebookFileInfo

Bases: TypedDict

Nested file info for notebook reads.

Source code in src/clawd_code_sdk/models/output_types.py
class ReadNotebookFileInfo(TypedDict):
    """Nested file info for notebook reads."""

    filePath: str
    cells: list[Any]

ReadNotebookOutput

Bases: TypedDict

tool_use_result for the Read tool (Jupyter notebooks).

Source code in src/clawd_code_sdk/models/output_types.py
class ReadNotebookOutput(TypedDict):
    """``tool_use_result`` for the Read tool (Jupyter notebooks)."""

    type: Literal["notebook"]
    file: ReadNotebookFileInfo

ReadPartsFileInfo

Bases: TypedDict

Nested file info for PDF parts (extracted page images).

Source code in src/clawd_code_sdk/models/output_types.py
class ReadPartsFileInfo(TypedDict):
    """Nested file info for PDF parts (extracted page images)."""

    filePath: str
    originalSize: int
    count: int
    """Number of pages extracted."""
    outputDir: str
    """Directory containing extracted page images."""

count instance-attribute

count: int

Number of pages extracted.

outputDir instance-attribute

outputDir: str

Directory containing extracted page images.

ReadPartsOutput

Bases: TypedDict

tool_use_result for the Read tool (PDF parts extraction).

Source code in src/clawd_code_sdk/models/output_types.py
class ReadPartsOutput(TypedDict):
    """``tool_use_result`` for the Read tool (PDF parts extraction)."""

    type: Literal["parts"]
    file: ReadPartsFileInfo
    firstPage: NotRequired[int]
    """First page number included as page images in the model-facing tool_result."""
    pages: NotRequired[list[ReadPartsPage]]
    """Page images (only present transiently in-process, absent on emitted results)."""

firstPage instance-attribute

firstPage: NotRequired[int]

First page number included as page images in the model-facing tool_result.

pages instance-attribute

pages: NotRequired[list[ReadPartsPage]]

Page images (only present transiently in-process, absent on emitted results).

ReadPdfFileInfo

Bases: TypedDict

Nested file info for PDF reads.

Source code in src/clawd_code_sdk/models/output_types.py
class ReadPdfFileInfo(TypedDict):
    """Nested file info for PDF reads."""

    filePath: str
    base64: str
    """Base64-encoded PDF data."""
    originalSize: int

base64 instance-attribute

base64: str

Base64-encoded PDF data.

ReadPdfOutput

Bases: TypedDict

tool_use_result for the Read tool (PDF files).

Source code in src/clawd_code_sdk/models/output_types.py
class ReadPdfOutput(TypedDict):
    """``tool_use_result`` for the Read tool (PDF files)."""

    type: Literal["pdf"]
    file: ReadPdfFileInfo

ReadTextOutput

Bases: TypedDict

tool_use_result for the Read tool (text files).

Source code in src/clawd_code_sdk/models/output_types.py
class ReadTextOutput(TypedDict):
    """``tool_use_result`` for the Read tool (text files)."""

    type: Literal["text"]
    file: ReadFileInfo
    artifactRead: NotRequired[ArtifactReadMarker]
    """Set when the read file is an artifact that now counts as viewed."""

artifactRead instance-attribute

artifactRead: NotRequired[ArtifactReadMarker]

Set when the read file is an artifact that now counts as viewed.

ReloadPluginsCacheImpact

Bases: BaseModel

How a reload would change the session's tool list.

Source code in src/clawd_code_sdk/models/control.py
class ReloadPluginsCacheImpact(BaseModel):
    """How a reload would change the session's tool list."""

    mcp_servers_added: list[str]
    mcp_servers_removed: list[str]
    lsp_tool_change: Literal["adds", "may-add", "removes", "may-remove"] | None

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.

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.

SDKContextUsage

Bases: ClaudeCodeBaseModel

Compact context usage snapshot, attached to assistant messages.

Source code in src/clawd_code_sdk/models/context_usage.py
class SDKContextUsage(ClaudeCodeBaseModel):
    """Compact context usage snapshot, attached to assistant messages."""

    model: str
    total_tokens: int
    raw_max_tokens: int
    percentage: float
    over_limit: SDKContextUsageOverLimit | None = None
    categories: list[SDKContextUsageCategory]
    mcp_tools: list[SDKContextUsageMcpTool]
    memory_files: list[SDKContextUsageMemoryFile]
    agents: list[SDKContextUsageAgent]
    skills: list[SDKContextUsageSkill] | None = None

SDKControlApplyFlagSettingsRequest

Bases: _ControlBase

SDK control apply flag settings request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlApplyFlagSettingsRequest(_ControlBase):
    """SDK control apply flag settings request."""

    subtype: Literal["apply_flag_settings"] = "apply_flag_settings"
    settings: dict[str, Any]

SDKControlBackgroundTasksRequest

Bases: _ControlBase

Moves running foreground tasks (or one tool use) to the background.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlBackgroundTasksRequest(_ControlBase):
    """Moves running foreground tasks (or one tool use) to the background."""

    subtype: Literal["background_tasks"] = "background_tasks"
    tool_use_id: str | None = None

SDKControlCancelAsyncMessageRequest

Bases: _ControlBase

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

Source code in src/clawd_code_sdk/models/control.py
class SDKControlCancelAsyncMessageRequest(_ControlBase):
    """Drops a pending async user message from the command queue by uuid."""

    subtype: Literal["cancel_async_message"] = "cancel_async_message"
    message_uuid: str

SDKControlChannelEnableRequest

Bases: _ControlBase

Enables MCP channel notifications for a marketplace plugin server.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlChannelEnableRequest(_ControlBase):
    """Enables MCP channel notifications for a marketplace plugin server."""

    subtype: Literal["channel_enable"] = "channel_enable"
    server_name: str = Field(serialization_alias="serverName")

SDKControlClaudeOAuthWaitForCompletionRequest

Bases: _ControlBase

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

Unlike claude_oauth_callback, this does not provide an authorization code — it simply waits for the existing OAuth flow (started by claude_authenticate) to finish. The response contains the authenticated account details.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlClaudeOAuthWaitForCompletionRequest(_ControlBase):
    """Waits for an in-progress Claude OAuth flow to complete.

    Unlike ``claude_oauth_callback``, this does not provide an authorization
    code — it simply waits for the existing OAuth flow (started by
    ``claude_authenticate``) to finish.  The response contains the
    authenticated account details.
    """

    subtype: Literal["claude_oauth_wait_for_completion"] = "claude_oauth_wait_for_completion"

SDKControlElicitationRequest

Bases: _ControlBase

Requests the SDK consumer to handle an MCP elicitation (user input request).

Source code in src/clawd_code_sdk/models/control.py
class SDKControlElicitationRequest(_ControlBase):
    """Requests the SDK consumer to handle an MCP elicitation (user input request)."""

    subtype: Literal["elicitation"] = "elicitation"
    mcp_server_name: str
    """Name of the MCP server requesting elicitation."""
    message: str
    """Message to display to the user."""
    mode: ElicitationMode | None = None
    """Elicitation mode: 'form' for structured input, 'url' for browser-based auth."""
    url: str | None = None
    """URL to open (only for 'url' mode)."""
    elicitation_id: str | None = None
    """Elicitation ID for correlating URL elicitations with completion notifications."""
    requested_schema: dict[str, Any] | None = None
    """JSON Schema for the requested input (only for 'form' mode)."""
    title: str | None = None
    """Permission-display title from the MCP server's _meta['anthropic/permissionDisplay'].

    Mirrors can_use_tool.title so SDK consumers can render elicitation-driven permission prompts
    with structured headers instead of parsing `message`.
    """
    display_name: str | None = None
    """Short tool/server label from `_meta['anthropic/permissionDisplay'].displayName`."""
    description: str | None = None
    """Permission-display description from `_meta['anthropic/permissionDisplay'].description`."""

    def to_mcp(self) -> mcp.types.ElicitRequestParams:
        """Convert to the corresponding MCP elicitation request params.

        Built from the wire format (camelCase keys, ``_meta``), which both
        mcp 1.x and 2.x accept, so this works on either major.
        """
        from mcp.types import ElicitRequestFormParams, ElicitRequestURLParams

        meta = {
            "anthropic/permissionDisplay": {
                "title": self.title,
                "displayName": self.display_name,
                "description": self.description,
            }
        }
        match self.mode:
            case "url":
                assert self.url is not None
                assert self.elicitation_id is not None
                return ElicitRequestURLParams.model_validate({
                    "mode": "url",
                    "message": self.message,
                    "url": self.url,
                    "elicitationId": self.elicitation_id,
                    "_meta": meta,
                })
            case "form":
                assert self.requested_schema is not None
                return ElicitRequestFormParams.model_validate({
                    "mode": "form",
                    "message": self.message,
                    "requestedSchema": self.requested_schema,
                    "_meta": meta,
                })
            case None:
                raise ValueError("mode must be 'url' or 'form'")
            case _ as unreachable:
                assert_never(unreachable)

    @classmethod
    def from_mcp(
        cls,
        params: mcp.types.ElicitRequestParams,
        mcp_server_name: str,
    ) -> SDKControlElicitationRequest:
        """Create from MCP elicitation request params (mcp 1.x or 2.x)."""
        wire = params.model_dump(by_alias=True, mode="json", exclude_none=True)
        display = (wire.get("_meta") or {}).get("anthropic/permissionDisplay") or {}
        common: dict[str, Any] = {
            "mcp_server_name": mcp_server_name,
            "message": wire["message"],
            "title": display.get("title"),
            "display_name": display.get("displayName"),
            "description": display.get("description"),
        }
        match wire:
            case {"url": str() as url, "elicitationId": str() as elicitation_id}:
                return cls(**common, mode="url", url=url, elicitation_id=elicitation_id)
            case {"requestedSchema": dict() as schema}:
                return cls(**common, mode="form", requested_schema=schema)
            case _:
                raise ValueError(f"Unsupported elicitation params: {sorted(wire)}")

description class-attribute instance-attribute

description: str | None = None

Permission-display description from _meta['anthropic/permissionDisplay'].description.

display_name class-attribute instance-attribute

display_name: str | None = None

Short tool/server label from _meta['anthropic/permissionDisplay'].displayName.

elicitation_id class-attribute instance-attribute

elicitation_id: str | None = None

Elicitation ID for correlating URL elicitations with completion notifications.

mcp_server_name instance-attribute

mcp_server_name: str

Name of the MCP server requesting elicitation.

message instance-attribute

message: str

Message to display to the user.

mode class-attribute instance-attribute

mode: ElicitationMode | None = None

Elicitation mode: 'form' for structured input, 'url' for browser-based auth.

requested_schema class-attribute instance-attribute

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

JSON Schema for the requested input (only for 'form' mode).

title class-attribute instance-attribute

title: str | None = None

Permission-display title from the MCP server's _meta['anthropic/permissionDisplay'].

Mirrors can_use_tool.title so SDK consumers can render elicitation-driven permission prompts with structured headers instead of parsing message.

url class-attribute instance-attribute

url: str | None = None

URL to open (only for 'url' mode).

from_mcp classmethod

from_mcp(params: ElicitRequestParams, mcp_server_name: str) -> SDKControlElicitationRequest

Create from MCP elicitation request params (mcp 1.x or 2.x).

Source code in src/clawd_code_sdk/models/control.py
@classmethod
def from_mcp(
    cls,
    params: mcp.types.ElicitRequestParams,
    mcp_server_name: str,
) -> SDKControlElicitationRequest:
    """Create from MCP elicitation request params (mcp 1.x or 2.x)."""
    wire = params.model_dump(by_alias=True, mode="json", exclude_none=True)
    display = (wire.get("_meta") or {}).get("anthropic/permissionDisplay") or {}
    common: dict[str, Any] = {
        "mcp_server_name": mcp_server_name,
        "message": wire["message"],
        "title": display.get("title"),
        "display_name": display.get("displayName"),
        "description": display.get("description"),
    }
    match wire:
        case {"url": str() as url, "elicitationId": str() as elicitation_id}:
            return cls(**common, mode="url", url=url, elicitation_id=elicitation_id)
        case {"requestedSchema": dict() as schema}:
            return cls(**common, mode="form", requested_schema=schema)
        case _:
            raise ValueError(f"Unsupported elicitation params: {sorted(wire)}")

to_mcp

to_mcp() -> ElicitRequestParams

Convert to the corresponding MCP elicitation request params.

Built from the wire format (camelCase keys, _meta), which both mcp 1.x and 2.x accept, so this works on either major.

Source code in src/clawd_code_sdk/models/control.py
def to_mcp(self) -> mcp.types.ElicitRequestParams:
    """Convert to the corresponding MCP elicitation request params.

    Built from the wire format (camelCase keys, ``_meta``), which both
    mcp 1.x and 2.x accept, so this works on either major.
    """
    from mcp.types import ElicitRequestFormParams, ElicitRequestURLParams

    meta = {
        "anthropic/permissionDisplay": {
            "title": self.title,
            "displayName": self.display_name,
            "description": self.description,
        }
    }
    match self.mode:
        case "url":
            assert self.url is not None
            assert self.elicitation_id is not None
            return ElicitRequestURLParams.model_validate({
                "mode": "url",
                "message": self.message,
                "url": self.url,
                "elicitationId": self.elicitation_id,
                "_meta": meta,
            })
        case "form":
            assert self.requested_schema is not None
            return ElicitRequestFormParams.model_validate({
                "mode": "form",
                "message": self.message,
                "requestedSchema": self.requested_schema,
                "_meta": meta,
            })
        case None:
            raise ValueError("mode must be 'url' or 'form'")
        case _ as unreachable:
            assert_never(unreachable)

SDKControlEndSessionRequest

Bases: _ControlBase

Ends the current session.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlEndSessionRequest(_ControlBase):
    """Ends the current session."""

    subtype: Literal["end_session"] = "end_session"

SDKControlFileSuggestionsRequest

Bases: _ControlBase

Requests at-mention file autocomplete suggestions for a partial path prefix.

Returns the same fuzzy-matched results the TUI shows.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlFileSuggestionsRequest(_ControlBase):
    """Requests at-mention file autocomplete suggestions for a partial path prefix.

    Returns the same fuzzy-matched results the TUI shows.
    """

    subtype: Literal["file_suggestions"] = "file_suggestions"
    query: str

SDKControlGenerateSessionTitleRequest

Bases: _ControlBase

Generates a title for a session from a description of it.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlGenerateSessionTitleRequest(_ControlBase):
    """Generates a title for a session from a description of it."""

    subtype: Literal["generate_session_title"] = "generate_session_title"
    description: str
    """Text to title, e.g. the conversation's latest user and assistant text."""
    persist: bool | None = None
    """Store the title as the current session's title. A session that has one already
    (the CLI titles new sessions itself) returns it instead of generating another."""

description instance-attribute

description: str

Text to title, e.g. the conversation's latest user and assistant text.

persist class-attribute instance-attribute

persist: bool | None = None

Store the title as the current session's title. A session that has one already (the CLI titles new sessions itself) returns it instead of generating another.

SDKControlGetBinaryVersionRequest

Bases: _ControlBase

Requests the version of the running Claude Code binary.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlGetBinaryVersionRequest(_ControlBase):
    """Requests the version of the running Claude Code binary."""

    subtype: Literal["get_binary_version"] = "get_binary_version"

SDKControlGetContextUsageRequest

Bases: _ControlBase

Requests a breakdown of current context window usage by category.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlGetContextUsageRequest(_ControlBase):
    """Requests a breakdown of current context window usage by category."""

    subtype: Literal["get_context_usage"] = "get_context_usage"
    detail: Literal["summary", "full"] | None = None

SDKControlGetContextUsageResponse

Bases: ClaudeCodeBaseModel

Breakdown of current context window usage by category.

Source code in src/clawd_code_sdk/models/context_usage.py
class SDKControlGetContextUsageResponse(ClaudeCodeBaseModel):
    """Breakdown of current context window usage by category."""

    categories: list[ContextUsageCategory]
    total_tokens: int
    max_tokens: int
    raw_max_tokens: int
    percentage: float
    grid_rows: list[list[ContextUsageGridCell]]
    model: str
    memory_files: list[ContextUsageMemoryFile]
    mcp_tools: list[ContextUsageMcpTool]
    mcp_instructions: list[ContextUsageMcpInstructions] | None = None
    deferred_builtin_tools: list[ContextUsageDeferredBuiltinTool] | None = None
    system_tools: list[ContextUsageSystemTool] | None = None
    system_prompt_sections: list[ContextUsageSystemPromptSection] | None = None
    agents: list[ContextUsageAgent]
    slash_commands: ContextUsageSlashCommands | None = None
    skills: ContextUsageSkills | None = None
    auto_compact_threshold: int | None = None
    autocompact_source: str | None = Field(default=None, alias="autocompactSource")
    """Where the auto-compact threshold came from, e.g. "model-default" (undocumented)."""
    is_auto_compact_enabled: bool
    message_breakdown: ContextUsageMessageBreakdown | None = None
    api_usage: Usage | None = None

autocompact_source class-attribute instance-attribute

autocompact_source: str | None = Field(default=None, alias='autocompactSource')

Where the auto-compact threshold came from, e.g. "model-default" (undocumented).

SDKControlGetHooksListingRequest

Bases: _ControlBase

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

Source code in src/clawd_code_sdk/models/control.py
class SDKControlGetHooksListingRequest(_ControlBase):
    """Requests the listing of configured hooks (same data as /hooks)."""

    subtype: Literal["get_hooks_listing"] = "get_hooks_listing"

SDKControlGetSettingsRequest

Bases: _ControlBase

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

Source code in src/clawd_code_sdk/models/control.py
class SDKControlGetSettingsRequest(_ControlBase):
    """Returns the effective merged settings and the raw per-source settings."""

    subtype: Literal["get_settings"] = "get_settings"

SDKControlGetTaskOutputRequest

Bases: _ControlBase

Reads the output collected so far for a background task.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlGetTaskOutputRequest(_ControlBase):
    """Reads the output collected so far for a background task."""

    subtype: Literal["get_task_output"] = "get_task_output"
    task_id: str

SDKControlGetTaskOutputResponse

Bases: BaseModel

Output of a background task.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlGetTaskOutputResponse(BaseModel):
    """Output of a background task."""

    output: str
    total_bytes: int
    truncated: bool

SDKControlGetUsageRequest

Bases: _ControlBase

Requests the structured usage report (session cost + rate limits). Experimental.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlGetUsageRequest(_ControlBase):
    """Requests the structured usage report (session cost + rate limits). Experimental."""

    subtype: Literal["get_usage"] = "get_usage"
    skip_behaviors: bool | None = None

SDKControlGetUsageResponse

Bases: ClaudeCodeBaseModel

Structured /usage data: session totals and plan rate-limit windows. Experimental.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlGetUsageResponse(ClaudeCodeBaseModel):
    """Structured /usage data: session totals and plan rate-limit windows. Experimental."""

    session: UsageReportSession
    """Cost and usage accumulated by the current session."""
    subscription_type: str | None
    """claude.ai plan (e.g. "pro", "max"), None without a subscription."""
    rate_limits_available: bool
    """False when plan limits do not apply (API key, Bedrock, Vertex, ...)."""
    rate_limits: UsageRateLimits | None
    behaviors: dict[str, Any] | None = None
    """What contributes to usage, from a scan of local transcripts (None if skipped)."""

behaviors class-attribute instance-attribute

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

What contributes to usage, from a scan of local transcripts (None if skipped).

rate_limits_available instance-attribute

rate_limits_available: bool

False when plan limits do not apply (API key, Bedrock, Vertex, ...).

session instance-attribute

Cost and usage accumulated by the current session.

subscription_type instance-attribute

subscription_type: str | None

claude.ai plan (e.g. "pro", "max"), None without a subscription.

SDKControlInitializeRequest

Bases: _ControlBase

SDK control initialize request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlInitializeRequest(_ControlBase):
    """SDK control initialize request."""

    subtype: Literal["initialize"] = "initialize"
    hooks: dict[HookEvent, Any] | None = None
    agents: dict[str, AgentWireDefinition] | None = None
    sdk_mcp_servers: list[str] | None = Field(default=None, serialization_alias="sdkMcpServers")
    sdk_mcp_server_configs: dict[str, dict[str, Any]] | None = Field(
        default=None, serialization_alias="sdkMcpServerConfigs"
    )
    """Settings of the in-process servers in ``sdk_mcp_servers``, by name: ``timeout`` (ms per
    tool call, when first registered) and ``tools`` (per-tool permission policy)."""
    sdk_mcp_server_manifests: dict[str, SdkMcpServerManifest] | None = Field(
        default=None, serialization_alias="sdkMcpServerManifests"
    )
    """The in-process servers' handshake results, captured by the host (a one-shot cache
    for the connect that follows; ``sdk_mcp_manifests_parked`` reports each entry)."""
    sdk_mcp_server_manifests_origin: Literal["host_per_send"] | None = Field(
        default=None, serialization_alias="sdkMcpServerManifestsOrigin"
    )
    """That the manifests were captured for this send (only needed over a remote session
    transport; the CLI's own stdio transport needs no marker)."""
    plugins: list[dict[str, Any]] | None = None
    """Plugins to load at launch (``plugin_delivery="initialize"``, ``--await-initialize``)."""
    mcp_servers: dict[str, dict[str, Any]] | None = Field(
        default=None, serialization_alias="mcpServers"
    )
    """Servers for Claude Code to run or connect to, as one ``--mcp-config`` item would hold
    them; read only at launch under ``--await-initialize`` (``mcp_servers_applied``)."""
    system_prompt: list[str] | None = Field(default=None, serialization_alias="systemPrompt")
    append_system_prompt: str | None = Field(default=None, serialization_alias="appendSystemPrompt")
    exclude_dynamic_sections: bool | None = Field(
        default=None,
        serialization_alias="excludeDynamicSections",
    )
    """When true, omit per-user dynamic sections from the cached system prompt.

    Omits info like working directory, auto-memory path and re-inject them as the first usermessage.
    Lets cross-user prompt caching hit on a static system prompt prefix.
    Tradeoff: the model sees this context slightly later in the prompt,
    so steering on the working directory and memory location is marginally less authoritative.
    Has no effect when a custom (non-preset) system prompt is in use."""
    json_schema: dict[str, Any] | None = Field(default=None, serialization_alias="jsonSchema")
    prompt_suggestions: bool | None = Field(default=None, serialization_alias="promptSuggestions")
    agent_progress_summaries: bool | None = Field(
        default=None, serialization_alias="agentProgressSummaries"
    )
    title: str | None = None
    """Custom session title.

    When provided, the session uses this title and skips automatic title generation.
    Has no effect on the persisted title when resuming an existing session."""
    skills: list[str] | None = None
    """When provided, only given skills are loaded into the main session system prompt.

    Uses the same rules as AgentDefinition.skills:
    exact name, plugin-qualified name, or ":name" suffix.
    Omit to load every discovered skill.
    Applies to the main session only; subagents use AgentDefinition.skills."""
    plan_mode_instructions: str | None = Field(
        default=None,
        serialization_alias="planModeInstructions",
    )
    """Custom workflow body for the plan-mode system reminder."""
    system_prompt_snapshot: bool | None = Field(
        default=None, serialization_alias="systemPromptSnapshot"
    )
    forward_subagent_text: bool | None = Field(
        default=None, serialization_alias="forwardSubagentText"
    )
    tool_aliases: dict[str, str] | None = Field(default=None, serialization_alias="toolAliases")
    per_task_stop_affordance: bool | None = Field(
        default=None, serialization_alias="perTaskStopAffordance"
    )
    supported_dialog_kinds: list[str] | None = Field(
        default=None, serialization_alias="supportedDialogKinds"
    )

exclude_dynamic_sections class-attribute instance-attribute

exclude_dynamic_sections: bool | None = Field(
    default=None, serialization_alias="excludeDynamicSections"
)

When true, omit per-user dynamic sections from the cached system prompt.

Omits info like working directory, auto-memory path and re-inject them as the first usermessage. Lets cross-user prompt caching hit on a static system prompt prefix. Tradeoff: the model sees this context slightly later in the prompt, so steering on the working directory and memory location is marginally less authoritative. Has no effect when a custom (non-preset) system prompt is in use.

mcp_servers class-attribute instance-attribute

mcp_servers: dict[str, dict[str, Any]] | None = Field(
    default=None, serialization_alias="mcpServers"
)

Servers for Claude Code to run or connect to, as one --mcp-config item would hold them; read only at launch under --await-initialize (mcp_servers_applied).

plan_mode_instructions class-attribute instance-attribute

plan_mode_instructions: str | None = Field(default=None, serialization_alias="planModeInstructions")

Custom workflow body for the plan-mode system reminder.

plugins class-attribute instance-attribute

plugins: list[dict[str, Any]] | None = None

Plugins to load at launch (plugin_delivery="initialize", --await-initialize).

sdk_mcp_server_configs class-attribute instance-attribute

sdk_mcp_server_configs: dict[str, dict[str, Any]] | None = Field(
    default=None, serialization_alias="sdkMcpServerConfigs"
)

Settings of the in-process servers in sdk_mcp_servers, by name: timeout (ms per tool call, when first registered) and tools (per-tool permission policy).

sdk_mcp_server_manifests class-attribute instance-attribute

sdk_mcp_server_manifests: dict[str, SdkMcpServerManifest] | None = Field(
    default=None, serialization_alias="sdkMcpServerManifests"
)

The in-process servers' handshake results, captured by the host (a one-shot cache for the connect that follows; sdk_mcp_manifests_parked reports each entry).

sdk_mcp_server_manifests_origin class-attribute instance-attribute

sdk_mcp_server_manifests_origin: Literal["host_per_send"] | None = Field(
    default=None, serialization_alias="sdkMcpServerManifestsOrigin"
)

That the manifests were captured for this send (only needed over a remote session transport; the CLI's own stdio transport needs no marker).

skills class-attribute instance-attribute

skills: list[str] | None = None

When provided, only given skills are loaded into the main session system prompt.

Uses the same rules as AgentDefinition.skills: exact name, plugin-qualified name, or ":name" suffix. Omit to load every discovered skill. Applies to the main session only; subagents use AgentDefinition.skills.

title class-attribute instance-attribute

title: str | None = None

Custom session title.

When provided, the session uses this title and skips automatic title generation. Has no effect on the persisted title when resuming an existing session.

SDKControlInterruptRequest

Bases: _ControlBase

SDK control interrupt request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlInterruptRequest(_ControlBase):
    """SDK control interrupt request."""

    subtype: Literal["interrupt"] = "interrupt"
    cancel_queued: bool | None = None
    """Also cancel queued (not yet started) user messages."""

cancel_queued class-attribute instance-attribute

cancel_queued: bool | None = None

Also cancel queued (not yet started) user messages.

SDKControlInterruptResponse

Bases: BaseModel

Response to an interrupt request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlInterruptResponse(BaseModel):
    """Response to an interrupt request."""

    still_queued: list[str] = Field(default_factory=list)
    """UUIDs of user messages still queued after the interrupt."""
    cancelled: list[str] | None = None
    """UUIDs of queued user messages that were cancelled."""

cancelled class-attribute instance-attribute

cancelled: list[str] | None = None

UUIDs of queued user messages that were cancelled.

still_queued class-attribute instance-attribute

still_queued: list[str] = Field(default_factory=list)

UUIDs of user messages still queued after the interrupt.

SDKControlListModelsRequest

Bases: _ControlBase

Requests the list of available models.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlListModelsRequest(_ControlBase):
    """Requests the list of available models."""

    subtype: Literal["list_models"] = "list_models"

SDKControlListPermissionRulesRequest

Bases: _ControlBase

Lists the effective permission rules.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlListPermissionRulesRequest(_ControlBase):
    """Lists the effective permission rules."""

    subtype: Literal["list_permission_rules"] = "list_permission_rules"

SDKControlMcpAuthenticateRequest

Bases: _ControlBase

Authenticates with an MCP server.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpAuthenticateRequest(_ControlBase):
    """Authenticates with an MCP server."""

    subtype: Literal["mcp_authenticate"] = "mcp_authenticate"
    server_name: str

SDKControlMcpCallRequest

Bases: _ControlBase

Invokes an MCP tool via the subprocess MCP client without a model turn.

No permission check (control channel is trusted, same as other subtypes). SDK-type MCP servers (config.type === "sdk") are rejected — they are caller-provided, so the caller can invoke them directly without the subprocess round-trip. Result content passes through the same processing as model-turn MCP calls. Session expiry is not retried automatically; callers can mcp_reconnect and retry. UrlElicitationRequired (-32042) tries Elicitation hooks; if no hook resolves, the call errors with the URL in the message — open it out-of-band, then retry mcp_call.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpCallRequest(_ControlBase):
    """Invokes an MCP tool via the subprocess MCP client without a model turn.

    No permission check (control channel is trusted, same as other subtypes).
    SDK-type MCP servers (config.type === "sdk") are rejected — they are caller-provided,
    so the caller can invoke them directly without the subprocess round-trip.
    Result content passes through the same processing as model-turn MCP calls.
    Session expiry is not retried automatically; callers can mcp_reconnect and retry.
    UrlElicitationRequired (-32042) tries Elicitation hooks;
    if no hook resolves, the call errors with the URL in the message
    — open it out-of-band, then retry mcp_call.
    """

    subtype: Literal["mcp_call"] = "mcp_call"
    tool: str
    arguments: dict[str, Any] | None = None

SDKControlMcpClearAuthRequest

Bases: _ControlBase

Clears authentication for an MCP server.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpClearAuthRequest(_ControlBase):
    """Clears authentication for an MCP server."""

    subtype: Literal["mcp_clear_auth"] = "mcp_clear_auth"
    server_name: str

SDKControlMcpMessageRequest

Bases: _ControlBase

SDK control MCP message request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpMessageRequest(_ControlBase):
    """SDK control MCP message request."""

    subtype: Literal["mcp_message"] = "mcp_message"
    server_name: str
    message: JSONRPCMessage

SDKControlMcpOAuthCallbackUrlRequest

Bases: _ControlBase

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

Sent by the SDK to the CLI with the full redirect URL (containing the authorization code) after the user completes browser-based OAuth.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpOAuthCallbackUrlRequest(_ControlBase):
    """Provides an OAuth redirect callback URL to complete an MCP server OAuth flow.

    Sent by the SDK to the CLI with the full redirect URL (containing the
    authorization code) after the user completes browser-based OAuth.
    """

    subtype: Literal["mcp_oauth_callback_url"] = "mcp_oauth_callback_url"
    server_name: str
    callback_url: str

SDKControlMcpReadResourceRequest

Bases: _ControlBase

Reads a resource from a connected MCP server.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpReadResourceRequest(_ControlBase):
    """Reads a resource from a connected MCP server."""

    subtype: Literal["mcp_read_resource"] = "mcp_read_resource"
    server_name: str = Field(serialization_alias="serverName")
    uri: str

SDKControlMcpReadResourceResponse

Bases: BaseModel

Contents of an MCP resource.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpReadResourceResponse(BaseModel):
    """Contents of an MCP resource."""

    contents: list[McpResourceContents]

SDKControlMcpReconnectRequest

Bases: _ControlBase

Reconnects a disconnected or failed MCP server.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpReconnectRequest(_ControlBase):
    """Reconnects a disconnected or failed MCP server."""

    subtype: Literal["mcp_reconnect"] = "mcp_reconnect"
    server_name: str = Field(serialization_alias="serverName")

SDKControlMcpSetServersRequest

Bases: _ControlBase

Replaces the set of dynamically managed MCP servers.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpSetServersRequest(_ControlBase):
    """Replaces the set of dynamically managed MCP servers."""

    subtype: Literal["mcp_set_servers"] = "mcp_set_servers"
    servers: dict[str, ExternalMcpServerConfig]

SDKControlMcpStatusRequest

Bases: _ControlBase

Requests the current status of all MCP server connections.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpStatusRequest(_ControlBase):
    """Requests the current status of all MCP server connections."""

    subtype: Literal["mcp_status"] = "mcp_status"
    live_reply: bool | None = Field(default=None, serialization_alias="liveReply")

SDKControlMcpToggleRequest

Bases: _ControlBase

Enables or disables an MCP server.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlMcpToggleRequest(_ControlBase):
    """Enables or disables an MCP server."""

    subtype: Literal["mcp_toggle"] = "mcp_toggle"
    server_name: str = Field(serialization_alias="serverName")
    enabled: bool

SDKControlPermissionRequest

Bases: _ControlBase

SDK control permission request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlPermissionRequest(_ControlBase):
    """SDK control permission request."""

    subtype: Literal["can_use_tool"] = "can_use_tool"
    tool_name: str
    input: dict[str, Any]
    permission_suggestions: list[PermissionUpdate] | None = None
    blocked_path: str | None = None
    decision_reason: str | None = None
    title: str | None = None
    display_name: str | None = None
    tool_use_id: str
    agent_id: str | None = None
    description: str | None = None
    decision_reason_type: DecisionReasonType | None = None
    """Structured discriminator for why auto-mode escalated.

    Lets SDK hosts make policy (e.g. auto-deny safetyCheck) without parsing decision_reason text.
    For compound bash commands this is "subcommandResults" even when a safetyCheck is nested inside
    — check classifier_approvable for that case.
    """
    classifier_approvable: bool | None = None
    """Set when a safetyCheck is present anywhere in the decision reason
    (including nested inside subcommandResults for compound bash).
    false = at least one safety check requires manual approval
    (e.g. Windows path bypass, dangerous rm);
    true = all safety checks MAY be classifier-approved
    (e.g. sensitive-file paths). Absent when no safetyCheck is involved."""

classifier_approvable class-attribute instance-attribute

classifier_approvable: bool | None = None

Set when a safetyCheck is present anywhere in the decision reason (including nested inside subcommandResults for compound bash). false = at least one safety check requires manual approval (e.g. Windows path bypass, dangerous rm); true = all safety checks MAY be classifier-approved (e.g. sensitive-file paths). Absent when no safetyCheck is involved.

decision_reason_type class-attribute instance-attribute

decision_reason_type: DecisionReasonType | None = None

Structured discriminator for why auto-mode escalated.

Lets SDK hosts make policy (e.g. auto-deny safetyCheck) without parsing decision_reason text. For compound bash commands this is "subcommandResults" even when a safetyCheck is nested inside — check classifier_approvable for that case.

SDKControlReadFileRequest

Bases: _ControlBase

Read a file from the session filesystem for the remote sidebar viewer.

Path is resolved against cwd and gated by the same read-permission rules as the Read tool.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlReadFileRequest(_ControlBase):
    """Read a file from the session filesystem for the remote sidebar viewer.

    Path is resolved against cwd and gated by the same read-permission rules as the Read tool.
    """

    subtype: Literal["read_file"] = "read_file"
    path: str
    max_bytes: int | None = None
    encoding: Literal["utf-8", "base64"] | None = None

SDKControlReadFileResponse

Bases: _ControlBase

File contents for the remote sidebar viewer.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlReadFileResponse(_ControlBase):
    """File contents for the remote sidebar viewer."""

    contents: str
    abs_path: str
    truncated: bool | None = None
    encoding: Literal["base64"] | None = None
    lossy: bool | None = None
    """True when non-UTF-8 bytes were replaced while decoding."""
    model_config = ConfigDict(alias_generator=to_camel)

lossy class-attribute instance-attribute

lossy: bool | None = None

True when non-UTF-8 bytes were replaced while decoding.

SDKControlRegisterRepoRootRequest

Bases: _ControlBase

Registers an additional repository root (like /add-dir).

Source code in src/clawd_code_sdk/models/control.py
class SDKControlRegisterRepoRootRequest(_ControlBase):
    """Registers an additional repository root (like /add-dir)."""

    subtype: Literal["register_repo_root"] = "register_repo_root"
    directory: str
    reload_claude_md: bool | None = None
    reload_plugins: bool | None = None
    reload_skills: bool | None = None

SDKControlReloadOutputStylesRequest

Bases: _ControlBase

Re-scans output styles from disk.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlReloadOutputStylesRequest(_ControlBase):
    """Re-scans output styles from disk."""

    subtype: Literal["reload_output_styles"] = "reload_output_styles"

SDKControlReloadOutputStylesResponse

Bases: BaseModel

Output styles after reload.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlReloadOutputStylesResponse(BaseModel):
    """Output styles after reload."""

    available_output_styles: list[str]

SDKControlReloadSkillsRequest

Bases: _ControlBase

Re-scans skills from disk.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlReloadSkillsRequest(_ControlBase):
    """Re-scans skills from disk."""

    subtype: Literal["reload_skills"] = "reload_skills"

SDKControlReloadSkillsResponse

Bases: BaseModel

Skills after reload.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlReloadSkillsResponse(BaseModel):
    """Skills after reload."""

    skills: list[ClaudeCodeCommandInfo]

SDKControlRemoteControlRequest

Bases: _ControlBase

Toggles 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. The response includes session_url, connect_url, and environment_id when enabling.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlRemoteControlRequest(_ControlBase):
    """Toggles 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.
    The response includes ``session_url``, ``connect_url``, and
    ``environment_id`` when enabling.
    """

    subtype: Literal["remote_control"] = "remote_control"
    enabled: bool = False

SDKControlRequest

Bases: _ControlBase

SDK control request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlRequest(_ControlBase):
    """SDK control request."""

    type: Literal["control_request"]
    request_id: str
    request: ControlRequestUnion

SDKControlResponse

Bases: TypedDict

SDK Control response.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlResponse(TypedDict):
    """SDK Control response."""

    type: Literal["control_response"]
    response: ControlResponse | ControlErrorResponse

SDKControlRewindFilesRequest

Bases: _ControlBase

SDK control rewind files request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlRewindFilesRequest(_ControlBase):
    """SDK control rewind files request."""

    subtype: Literal["rewind_files"] = "rewind_files"
    user_message_id: str
    dry_run: bool | None = None

SDKControlSeedReadStateRequest

Bases: _ControlBase

Seeds the readFileState cache with a path+mtime entry.

Use when a prior Read was removed from context (e.g. by snip) so Edit validation would fail despite the client having observed the Read.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlSeedReadStateRequest(_ControlBase):
    """Seeds the readFileState cache with a path+mtime entry.

    Use when a prior Read was removed from context (e.g. by snip) so Edit
    validation would fail despite the client having observed the Read.
    """

    subtype: Literal["seed_read_state"] = "seed_read_state"
    path: str
    mtime: int

SDKControlSetHasSubscribersRequest

Bases: _ControlBase

Tells the CLI whether anyone is watching the session output.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlSetHasSubscribersRequest(_ControlBase):
    """Tells the CLI whether anyone is watching the session output."""

    subtype: Literal["set_has_subscribers"] = "set_has_subscribers"
    has_subscribers: bool | None

SDKControlSetMaxThinkingTokensRequest

Bases: _ControlBase

Sets the maximum number of thinking tokens for extended thinking.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlSetMaxThinkingTokensRequest(_ControlBase):
    """Sets the maximum number of thinking tokens for extended thinking."""

    subtype: Literal["set_max_thinking_tokens"] = "set_max_thinking_tokens"
    max_thinking_tokens: int | None = None
    thinking_display: Literal["summarized", "omitted", "highlights"] | None = None

SDKControlSetModelRequest

Bases: _ControlBase

Sets the model to use for subsequent conversation turns.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlSetModelRequest(_ControlBase):
    """Sets the model to use for subsequent conversation turns."""

    subtype: Literal["set_model"] = "set_model"
    model: ModelName | str | None = None

SDKControlSetPermissionModeRequest

Bases: _ControlBase

SDK control set permission mode request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlSetPermissionModeRequest(_ControlBase):
    """SDK control set permission mode request."""

    subtype: Literal["set_permission_mode"] = "set_permission_mode"
    mode: PermissionMode

SDKControlSetPermissionModeResponse

Bases: BaseModel

Response to a set_permission_mode request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlSetPermissionModeResponse(BaseModel):
    """Response to a set_permission_mode request."""

    mode: PermissionMode | None = None
    """The permission mode now in effect, which can differ from the one asked for."""

mode class-attribute instance-attribute

mode: PermissionMode | None = None

The permission mode now in effect, which can differ from the one asked for.

SDKControlSetProactiveRequest

Bases: _ControlBase

Sets proactive mode configuration.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlSetProactiveRequest(_ControlBase):
    """Sets proactive mode configuration."""

    subtype: Literal["set_proactive"] = "set_proactive"

SDKControlSideQuestionRequest

Bases: _ControlBase

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

This allows the SDK consumer to ask the model a question without adding it to the main conversation history. The CLI executes the question against the current context and returns the model's response.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlSideQuestionRequest(_ControlBase):
    """Sends a side question to the model using the current conversation context.

    This allows the SDK consumer to ask the model a question without adding
    it to the main conversation history.  The CLI executes the question
    against the current context and returns the model's response.
    """

    subtype: Literal["side_question"] = "side_question"
    question: str

SDKControlStopTaskRequest

Bases: _ControlBase

SDK control stop task request.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlStopTaskRequest(_ControlBase):
    """SDK control stop task request."""

    subtype: Literal["stop_task"] = "stop_task"
    task_id: str

SDKControlUpdateSettingsRequest

Bases: _ControlBase

Writes settings to the local or user settings file.

Source code in src/clawd_code_sdk/models/control.py
class SDKControlUpdateSettingsRequest(_ControlBase):
    """Writes settings to the local or user settings file."""

    subtype: Literal["update_settings"] = "update_settings"
    source: Literal["localSettings", "userSettings"]
    settings: dict[str, Any]

SDKDeferredToolUse

Bases: TypedDict

A deferred tool use from a completed agent result.

Source code in src/clawd_code_sdk/models/output_types.py
class SDKDeferredToolUse(TypedDict):
    """A deferred tool use from a completed agent result."""

    id: str
    """Tool use ID."""
    name: str
    """Tool name."""
    input: dict[str, Any]
    """Tool input parameters."""

id instance-attribute

id: str

Tool use ID.

input instance-attribute

input: dict[str, Any]

Tool input parameters.

name instance-attribute

name: str

Tool name.

SDKHookCallbackRequest

Bases: _ControlBase

SDK hook callback request.

Source code in src/clawd_code_sdk/models/control.py
class SDKHookCallbackRequest(_ControlBase):
    """SDK hook callback request."""

    subtype: Literal["hook_callback"] = "hook_callback"
    callback_id: str
    input: HookInput
    tool_use_id: str | None = None

SDKPermissionDenial

Bases: TypedDict

Permission denial from Claude API response.

Source code in src/clawd_code_sdk/models/messages.py
class SDKPermissionDenial(TypedDict):
    """Permission denial from Claude API response."""

    tool_name: ToolName | str
    tool_use_id: str
    tool_input: ToolInput | dict[str, Any]

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.

SDKUsageReport

Bases: ClaudeCodeBaseModel

Session usage report (same data as /usage).

Source code in src/clawd_code_sdk/models/context_usage.py
class SDKUsageReport(ClaudeCodeBaseModel):
    """Session usage report (same data as /usage)."""

    session: UsageReportSession
    rate_limits: UsageReportRateLimits | None

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

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.

SessionEndHookInput

Bases: BaseHookInput

Input data for SessionEnd hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class SessionEndHookInput(BaseHookInput):
    """Input data for SessionEnd hook events."""

    hook_event_name: Literal["SessionEnd"]
    reason: SessionEndReason

SessionKey

Bases: TypedDict

Identifies a session transcript or subagent transcript in the store.

Source code in src/clawd_code_sdk/models/system_messages.py
class SessionKey(TypedDict):
    """Identifies a session transcript or subagent transcript in the store."""

    projectKey: str
    """Caller-defined scope. Default: sanitized cwd."""
    sessionId: str
    subpath: str | None
    """Set for subagent files, None for main transcript."""

projectKey instance-attribute

projectKey: str

Caller-defined scope. Default: sanitized cwd.

subpath instance-attribute

subpath: str | None

Set for subagent files, None for main transcript.

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.

SessionStartHookInput

Bases: BaseHookInput

Input data for SessionStart hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class SessionStartHookInput(BaseHookInput):
    """Input data for SessionStart hook events."""

    hook_event_name: Literal["SessionStart"]
    source: Literal["startup", "resume", "clear", "compact"]
    agent_type: NotRequired[str]
    model: NotRequired[str]

SessionStartHookSpecificOutput

Bases: TypedDict

Hook-specific output for SessionStart events.

Source code in src/clawd_code_sdk/models/hooks.py
class SessionStartHookSpecificOutput(TypedDict):
    """Hook-specific output for SessionStart events."""

    hookEventName: Literal["SessionStart"]
    additionalContext: NotRequired[str]
    initialUserMessage: NotRequired[str]
    watchPaths: NotRequired[list[str]]

SessionStateChangedMessage

Bases: BaseSystemMessage

System message emitted when session state changes.

'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.

Source code in src/clawd_code_sdk/models/system_messages.py
class SessionStateChangedMessage(BaseSystemMessage):
    """System message emitted when session state changes.

    'idle' fires after heldBackResult flushes and the bg-agent do-while exits —
    authoritative turn-over signal.
    """

    subtype: Literal["session_state_changed"] = "session_state_changed"
    state: SessionState

SessionWritesLostMessage

Bases: BaseSystemMessage

Emitted when writes were lost due to a full disk or exceeded quota.

Source code in src/clawd_code_sdk/models/system_messages.py
class SessionWritesLostMessage(BaseSystemMessage):
    """Emitted when writes were lost due to a full disk or exceeded quota."""

    subtype: Literal["session_writes_lost"] = "session_writes_lost"
    error_code: Literal["ENOSPC", "EDQUOT"]
    lost: list[Literal["transcript", "global_config"]]
    transcript_session_ids: list[str] | None = None

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').

SetupHookInput

Bases: BaseHookInput

Input data for Setup hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class SetupHookInput(BaseHookInput):
    """Input data for Setup hook events."""

    hook_event_name: Literal["Setup"]
    trigger: Literal["init", "maintenance"]

SideQuestionResponse

Bases: ClaudeCodeBaseModel

Response from a side question.

Source code in src/clawd_code_sdk/models/control.py
class SideQuestionResponse(ClaudeCodeBaseModel):
    """Response from a side question."""

    response: str | None = None
    """The model's answer, or None if no context was available."""

response class-attribute instance-attribute

response: str | None = None

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

SkillInput

Bases: TypedDict

Input for the Skill tool. Invokes a named skill (slash command).

Not part of the official SDK ToolInputSchemas as of SDK v0.2.62. Shape derived from empirical testing.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class SkillInput(TypedDict):
    """Input for the Skill tool. Invokes a named skill (slash command).

    Not part of the official SDK ToolInputSchemas as of SDK v0.2.62.
    Shape derived from empirical testing.
    """

    skill: str
    """The skill name (e.g., "commit", "review", "debug")."""
    args: NotRequired[str]
    """Optional arguments for the skill."""

args instance-attribute

args: NotRequired[str]

Optional arguments for the skill.

skill instance-attribute

skill: str

The skill name (e.g., "commit", "review", "debug").

SkillOutput

Bases: TypedDict

tool_use_result for the Skill tool.

Not part of the official SDK ToolOutputSchemas as of SDK v0.2.62. Shape derived from empirical testing.

Source code in src/clawd_code_sdk/models/output_types.py
class SkillOutput(TypedDict):
    """``tool_use_result`` for the Skill tool.

    Not part of the official SDK ToolOutputSchemas as of SDK v0.2.62.
    Shape derived from empirical testing.
    """

    success: bool
    """Whether the skill was invoked successfully."""
    commandName: str
    """The name of the skill that was invoked."""
    allowedTools: list[ToolName | str]
    """Tools that the skill is allowed to use."""

allowedTools instance-attribute

allowedTools: list[ToolName | str]

Tools that the skill is allowed to use.

commandName instance-attribute

commandName: str

The name of the skill that was invoked.

success instance-attribute

success: bool

Whether the skill was invoked successfully.

StatusSystemMessage

Bases: BaseSystemMessage

System status message.

Source code in src/clawd_code_sdk/models/system_messages.py
class StatusSystemMessage(BaseSystemMessage):
    """System status message."""

    subtype: Literal["status"] = "status"
    status: SDKStatus
    permission_mode: PermissionMode | None = Field(None, validation_alias="permissionMode")
    compact_result: Literal["success", "failed"] | None = None
    compact_error: str | None = None
    user_message_uuids: list[str] | None = None
    """Client uuids of the user messages the turn takes in (undocumented, CLI 2.1.330+)."""

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+).

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

StopHookSpecificOutput

Bases: TypedDict

Hook-specific output for Stop events.

Source code in src/clawd_code_sdk/models/hooks.py
class StopHookSpecificOutput(TypedDict):
    """Hook-specific output for Stop events."""

    hookEventName: Literal["Stop"]
    additionalContext: NotRequired[str]

StreamEvent

Bases: BaseMessage

Stream event for partial message updates during streaming.

Source code in src/clawd_code_sdk/models/messages.py
class StreamEvent(BaseMessage):
    """Stream event for partial message updates during streaming."""

    type: Literal["stream_event"] = "stream_event"
    session_id: str
    event: BetaRawMessageStreamEvent
    parent_tool_use_id: str | None = None
    ttft_ms: float | None = None
    user_message_uuid: str | None = None
    user_message_uuids: list[str] | None = None
    resume_reason: str | None = None
    api_message_id: str | None = None
    """ID of the API message this event belongs to (undocumented)."""
    thinking_display: str | None = None
    """Active thinking display mode (undocumented)."""
    owed_rows: list[str] | None = None
    """Uuids of transcript rows the turn wrote before its first model request that change
    what Claude holds of a claude.ai Project or an attached PDF (internal, CLI 2.1.330+)."""

    @classmethod
    def block_stop(cls, *, index: int, session_id: str, uuid: str) -> StreamEvent:
        """Create a synthetic content_block_stop StreamEvent."""
        from anthropic.types.beta import BetaRawContentBlockStopEvent

        stop_event = BetaRawContentBlockStopEvent(type="content_block_stop", index=index)
        return StreamEvent(event=stop_event, session_id=session_id, uuid=uuid)

    @classmethod
    def message_stop(cls, *, session_id: str, uuid: str) -> StreamEvent:
        """Create a synthetic message_stop StreamEvent."""
        from anthropic.types.beta import BetaRawMessageStopEvent

        stop_event = BetaRawMessageStopEvent(type="message_stop")
        return StreamEvent(event=stop_event, session_id=session_id, uuid=uuid)

    @classmethod
    def block_start_text(cls, *, index: int, session_id: str, uuid: str) -> StreamEvent:
        """Create a synthetic content_block_start StreamEvent for a text block."""
        content_block = ATextBlock(type="text", text="")
        start_event = BetaRawContentBlockStartEvent(
            type="content_block_start", index=index, content_block=content_block
        )
        return StreamEvent(event=start_event, session_id=session_id, uuid=uuid)

    @classmethod
    def block_start_thinking(cls, *, index: int, session_id: str, uuid: str) -> StreamEvent:
        """Create a synthetic content_block_start StreamEvent for a thinking block."""
        content_block = AThinkingBlock(type="thinking", thinking="", signature="")
        start_event = BetaRawContentBlockStartEvent(
            type="content_block_start", index=index, content_block=content_block
        )
        return StreamEvent(event=start_event, session_id=session_id, uuid=uuid)

    @classmethod
    def block_start_tool_use(
        cls, *, tool_use_id: str, name: str, index: int, session_id: str, uuid: str
    ) -> StreamEvent:
        """Create a synthetic content_block_start StreamEvent for a tool_use block."""
        content_block = AToolUseBlock(type="tool_use", id=tool_use_id, name=name, input={})
        start_event = BetaRawContentBlockStartEvent(
            type="content_block_start", index=index, content_block=content_block
        )
        return StreamEvent(event=start_event, session_id=session_id, uuid=uuid)

    @classmethod
    def block_text_delta(cls, *, text: str, index: int, session_id: str, uuid: str) -> StreamEvent:
        """Create a synthetic content_block_delta StreamEvent with full block content."""
        delta_event = BetaRawContentBlockDeltaEvent(
            type="content_block_delta",
            index=index,
            delta=BetaTextDelta(type="text_delta", text=text),
        )
        return StreamEvent(event=delta_event, session_id=session_id, uuid=uuid)

    @classmethod
    def block_thinking_delta(
        cls,
        *,
        thinking: str,
        index: int,
        session_id: str,
        uuid: str,
    ) -> StreamEvent:
        """Create a synthetic content_block_delta StreamEvent with full block content."""
        delta_event = BetaRawContentBlockDeltaEvent(
            type="content_block_delta",
            index=index,
            delta=BetaThinkingDelta(type="thinking_delta", thinking=thinking),
        )
        return StreamEvent(event=delta_event, session_id=session_id, uuid=uuid)

    @classmethod
    def block_tool_json_delta(
        cls,
        *,
        partial_json: str,
        index: int,
        session_id: str,
        uuid: str,
    ) -> StreamEvent:
        """Create a synthetic content_block_delta StreamEvent with full block content."""
        delta_event = BetaRawContentBlockDeltaEvent(
            type="content_block_delta",
            index=index,
            delta=BetaInputJSONDelta(type="input_json_delta", partial_json=partial_json),
        )
        return StreamEvent(event=delta_event, session_id=session_id, uuid=uuid)

    @classmethod
    def message_delta(
        cls,
        *,
        stop_reason: BetaStopReason | None,
        session_id: str,
        uuid: str,
    ) -> StreamEvent:
        """Create a synthetic message_delta StreamEvent."""
        usage = BetaMessageDeltaUsage(output_tokens=0)
        delta = BetaRawMessageDelta(stop_reason=stop_reason)
        delta_event = BetaRawMessageDeltaEvent(type="message_delta", delta=delta, usage=usage)
        return StreamEvent(event=delta_event, session_id=session_id, uuid=uuid)

api_message_id class-attribute instance-attribute

api_message_id: str | None = None

ID of the API message this event belongs to (undocumented).

owed_rows class-attribute instance-attribute

owed_rows: list[str] | None = None

Uuids of transcript rows the turn wrote before its first model request that change what Claude holds of a claude.ai Project or an attached PDF (internal, CLI 2.1.330+).

thinking_display class-attribute instance-attribute

thinking_display: str | None = None

Active thinking display mode (undocumented).

block_start_text classmethod

block_start_text(*, index: int, session_id: str, uuid: str) -> StreamEvent

Create a synthetic content_block_start StreamEvent for a text block.

Source code in src/clawd_code_sdk/models/messages.py
@classmethod
def block_start_text(cls, *, index: int, session_id: str, uuid: str) -> StreamEvent:
    """Create a synthetic content_block_start StreamEvent for a text block."""
    content_block = ATextBlock(type="text", text="")
    start_event = BetaRawContentBlockStartEvent(
        type="content_block_start", index=index, content_block=content_block
    )
    return StreamEvent(event=start_event, session_id=session_id, uuid=uuid)

block_start_thinking classmethod

block_start_thinking(*, index: int, session_id: str, uuid: str) -> StreamEvent

Create a synthetic content_block_start StreamEvent for a thinking block.

Source code in src/clawd_code_sdk/models/messages.py
@classmethod
def block_start_thinking(cls, *, index: int, session_id: str, uuid: str) -> StreamEvent:
    """Create a synthetic content_block_start StreamEvent for a thinking block."""
    content_block = AThinkingBlock(type="thinking", thinking="", signature="")
    start_event = BetaRawContentBlockStartEvent(
        type="content_block_start", index=index, content_block=content_block
    )
    return StreamEvent(event=start_event, session_id=session_id, uuid=uuid)

block_start_tool_use classmethod

block_start_tool_use(
    *, tool_use_id: str, name: str, index: int, session_id: str, uuid: str
) -> StreamEvent

Create a synthetic content_block_start StreamEvent for a tool_use block.

Source code in src/clawd_code_sdk/models/messages.py
@classmethod
def block_start_tool_use(
    cls, *, tool_use_id: str, name: str, index: int, session_id: str, uuid: str
) -> StreamEvent:
    """Create a synthetic content_block_start StreamEvent for a tool_use block."""
    content_block = AToolUseBlock(type="tool_use", id=tool_use_id, name=name, input={})
    start_event = BetaRawContentBlockStartEvent(
        type="content_block_start", index=index, content_block=content_block
    )
    return StreamEvent(event=start_event, session_id=session_id, uuid=uuid)

block_stop classmethod

block_stop(*, index: int, session_id: str, uuid: str) -> StreamEvent

Create a synthetic content_block_stop StreamEvent.

Source code in src/clawd_code_sdk/models/messages.py
@classmethod
def block_stop(cls, *, index: int, session_id: str, uuid: str) -> StreamEvent:
    """Create a synthetic content_block_stop StreamEvent."""
    from anthropic.types.beta import BetaRawContentBlockStopEvent

    stop_event = BetaRawContentBlockStopEvent(type="content_block_stop", index=index)
    return StreamEvent(event=stop_event, session_id=session_id, uuid=uuid)

block_text_delta classmethod

block_text_delta(*, text: str, index: int, session_id: str, uuid: str) -> StreamEvent

Create a synthetic content_block_delta StreamEvent with full block content.

Source code in src/clawd_code_sdk/models/messages.py
@classmethod
def block_text_delta(cls, *, text: str, index: int, session_id: str, uuid: str) -> StreamEvent:
    """Create a synthetic content_block_delta StreamEvent with full block content."""
    delta_event = BetaRawContentBlockDeltaEvent(
        type="content_block_delta",
        index=index,
        delta=BetaTextDelta(type="text_delta", text=text),
    )
    return StreamEvent(event=delta_event, session_id=session_id, uuid=uuid)

block_thinking_delta classmethod

block_thinking_delta(*, thinking: str, index: int, session_id: str, uuid: str) -> StreamEvent

Create a synthetic content_block_delta StreamEvent with full block content.

Source code in src/clawd_code_sdk/models/messages.py
@classmethod
def block_thinking_delta(
    cls,
    *,
    thinking: str,
    index: int,
    session_id: str,
    uuid: str,
) -> StreamEvent:
    """Create a synthetic content_block_delta StreamEvent with full block content."""
    delta_event = BetaRawContentBlockDeltaEvent(
        type="content_block_delta",
        index=index,
        delta=BetaThinkingDelta(type="thinking_delta", thinking=thinking),
    )
    return StreamEvent(event=delta_event, session_id=session_id, uuid=uuid)

block_tool_json_delta classmethod

block_tool_json_delta(*, partial_json: str, index: int, session_id: str, uuid: str) -> StreamEvent

Create a synthetic content_block_delta StreamEvent with full block content.

Source code in src/clawd_code_sdk/models/messages.py
@classmethod
def block_tool_json_delta(
    cls,
    *,
    partial_json: str,
    index: int,
    session_id: str,
    uuid: str,
) -> StreamEvent:
    """Create a synthetic content_block_delta StreamEvent with full block content."""
    delta_event = BetaRawContentBlockDeltaEvent(
        type="content_block_delta",
        index=index,
        delta=BetaInputJSONDelta(type="input_json_delta", partial_json=partial_json),
    )
    return StreamEvent(event=delta_event, session_id=session_id, uuid=uuid)

message_delta classmethod

message_delta(*, stop_reason: BetaStopReason | None, session_id: str, uuid: str) -> StreamEvent

Create a synthetic message_delta StreamEvent.

Source code in src/clawd_code_sdk/models/messages.py
@classmethod
def message_delta(
    cls,
    *,
    stop_reason: BetaStopReason | None,
    session_id: str,
    uuid: str,
) -> StreamEvent:
    """Create a synthetic message_delta StreamEvent."""
    usage = BetaMessageDeltaUsage(output_tokens=0)
    delta = BetaRawMessageDelta(stop_reason=stop_reason)
    delta_event = BetaRawMessageDeltaEvent(type="message_delta", delta=delta, usage=usage)
    return StreamEvent(event=delta_event, session_id=session_id, uuid=uuid)

message_stop classmethod

message_stop(*, session_id: str, uuid: str) -> StreamEvent

Create a synthetic message_stop StreamEvent.

Source code in src/clawd_code_sdk/models/messages.py
@classmethod
def message_stop(cls, *, session_id: str, uuid: str) -> StreamEvent:
    """Create a synthetic message_stop StreamEvent."""
    from anthropic.types.beta import BetaRawMessageStopEvent

    stop_event = BetaRawMessageStopEvent(type="message_stop")
    return StreamEvent(event=stop_event, session_id=session_id, uuid=uuid)

StructuredPatchHunk

Bases: TypedDict

A single hunk in a structured patch.

Source code in src/clawd_code_sdk/models/output_types.py
class StructuredPatchHunk(TypedDict):
    """A single hunk in a structured patch."""

    oldStart: int
    oldLines: int
    newStart: int
    newLines: int
    lines: list[str]
    """Diff lines prefixed with ``' '`` (context), ``'+'`` (added), or ``'-'`` (removed)."""

lines instance-attribute

lines: list[str]

Diff lines prefixed with ' ' (context), '+' (added), or '-' (removed).

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

SubagentStopHookSpecificOutput

Bases: TypedDict

Hook-specific output for SubagentStop events.

Source code in src/clawd_code_sdk/models/hooks.py
class SubagentStopHookSpecificOutput(TypedDict):
    """Hook-specific output for SubagentStop events."""

    hookEventName: Literal["SubagentStop"]
    additionalContext: NotRequired[str]

SyncHookJSONOutput

Bases: TypedDict

Synchronous hook output with control and decision fields.

This defines the structure for hook callbacks to control execution and provide feedback to Claude.

Common Control Fields

continue_: Whether Claude should proceed after hook execution (default: True). Note: This is converted to "continue" when sent to the CLI. suppressOutput: Hide stdout from transcript mode (default: False). stopReason: Message shown when continue is False.

Decision Fields

decision: Set to "block" to indicate blocking behavior. systemMessage: Warning message displayed to the user. reason: Feedback message for Claude about the decision.

Hook-Specific Output

hookSpecificOutput: Event-specific controls (e.g., permissionDecision for PreToolUse, additionalContext for PostToolUse).

Note: The CLI documentation shows field names without underscores ("async", "continue"), but Python code should use the underscore versions ("async_", "continue_") as they are automatically converted.

Source code in src/clawd_code_sdk/models/hooks.py
class SyncHookJSONOutput(TypedDict):
    """Synchronous hook output with control and decision fields.

    This defines the structure for hook callbacks to control execution and provide
    feedback to Claude.

    Common Control Fields:
        continue_: Whether Claude should proceed after hook execution (default: True).
            Note: This is converted to "continue" when sent to the CLI.
        suppressOutput: Hide stdout from transcript mode (default: False).
        stopReason: Message shown when continue is False.

    Decision Fields:
        decision: Set to "block" to indicate blocking behavior.
        systemMessage: Warning message displayed to the user.
        reason: Feedback message for Claude about the decision.

    Hook-Specific Output:
        hookSpecificOutput: Event-specific controls (e.g., permissionDecision for
            PreToolUse, additionalContext for PostToolUse).

    Note: The CLI documentation shows field names without underscores ("async", "continue"),
    but Python code should use the underscore versions ("async_", "continue_") as they
    are automatically converted.
    """

    # Common control fields
    continue_: NotRequired[bool]  # Avoid name clash (converted to "continue" for CLI)
    suppressOutput: NotRequired[bool]
    stopReason: NotRequired[str]
    # Decision fields
    # Note: "approve" is deprecated for PreToolUse (use permissionDecision instead)
    # For other hooks, only "block" is meaningful
    decision: NotRequired[Literal["approve", "block"]]
    systemMessage: NotRequired[str]
    terminalSequence: NotRequired[str]
    reason: NotRequired[str]
    # Hook-specific outputs
    hookSpecificOutput: NotRequired[HookSpecificOutput]

TaskCompletedHookInput

Bases: BaseHookInput

Input data for TaskCompleted hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class TaskCompletedHookInput(BaseHookInput):
    """Input data for TaskCompleted hook events."""

    hook_event_name: Literal["TaskCompleted"]
    task_id: str
    task_subject: str
    task_description: NotRequired[str]
    teammate_name: NotRequired[str]
    team_name: NotRequired[str]

TaskCreatedHookInput

Bases: BaseHookInput

Input data for TaskCreated hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class TaskCreatedHookInput(BaseHookInput):
    """Input data for TaskCreated hook events."""

    hook_event_name: Literal["TaskCreated"]
    task_id: str
    task_subject: str
    task_description: NotRequired[str]
    teammate_name: NotRequired[str]
    team_name: NotRequired[str]

TaskInfo

Bases: TypedDict

Information about a background task.

Source code in src/clawd_code_sdk/models/output_types.py
class TaskInfo(TypedDict):
    """Information about a background task."""

    task_id: str
    task_type: Literal["local_bash", "agent"]
    status: Status
    description: str
    output: str
    exitCode: int | None

TaskNotificationSystemMessage

Bases: BaseSystemMessage

System message emitted when a subagent task completes, fails, or stops.

Source code in src/clawd_code_sdk/models/system_messages.py
class TaskNotificationSystemMessage(BaseSystemMessage):
    """System message emitted when a subagent task completes, fails, or stops."""

    subtype: Literal["task_notification"] = "task_notification"
    task_id: str
    run_id: str | None = None
    status: TaskStatus
    reason: Literal["worker_restart"] | None = None
    output_file: str
    summary: str
    tool_use_id: str | None = None
    usage: TaskProgressUsage | None = None
    resource_links: list[McpResourceLink] | None = None
    skip_transcript: bool | None = None
    """Whether to skip this message in the transcript."""
    ambient: bool | None = None

skip_transcript class-attribute instance-attribute

skip_transcript: bool | None = None

Whether to skip this message in the transcript.

TaskOutputResult

Bases: TypedDict

tool_use_result for the TaskOutput tool (background task polling).

Source code in src/clawd_code_sdk/models/output_types.py
class TaskOutputResult(TypedDict):
    """``tool_use_result`` for the TaskOutput tool (background task polling)."""

    retrieval_status: Literal["completed", "timeout", "running"]
    """Status of the retrieval."""
    task: TaskInfo

retrieval_status instance-attribute

retrieval_status: Literal['completed', 'timeout', 'running']

Status of the retrieval.

TaskProgressSystemMessage

Bases: BaseSystemMessage

System message emitted periodically with task progress updates.

Source code in src/clawd_code_sdk/models/system_messages.py
class TaskProgressSystemMessage(BaseSystemMessage):
    """System message emitted periodically with task progress updates."""

    subtype: Literal["task_progress"] = "task_progress"
    task_id: str
    run_id: str | None = None
    tool_use_id: str | None = None
    description: str
    subagent_type: str | None = None
    usage: TaskProgressUsage
    last_tool_name: ToolName | str | None = None
    summary: str | None = None
    """AI-generated progress summary when agentProgressSummaries is enabled."""

summary class-attribute instance-attribute

summary: str | None = None

AI-generated progress summary when agentProgressSummaries is enabled.

TaskProgressUsage

Bases: TypedDict

Usage info for a task progress update.

Source code in src/clawd_code_sdk/models/system_messages.py
class TaskProgressUsage(TypedDict):
    """Usage info for a task progress update."""

    total_tokens: int
    tool_uses: int
    duration_ms: int

TaskStartedSystemMessage

Bases: BaseSystemMessage

System message emitted when a subagent task starts.

Source code in src/clawd_code_sdk/models/system_messages.py
class TaskStartedSystemMessage(BaseSystemMessage):
    """System message emitted when a subagent task starts."""

    subtype: Literal["task_started"] = "task_started"
    task_id: str
    run_id: str | None = None
    tool_use_id: str | None = None
    description: str
    subagent_type: str | None = None
    is_backgrounded: bool | None = None
    spawn_depth: int | None = None
    parent_task_id: str | None = None
    task_type: str | None = None
    workflow_name: str | None = None
    """meta.name from the workflow script (e.g. 'spec').

    Only set when task_type is 'local_workflow'."""
    prompt: str | None = None
    skip_transcript: bool | None = None
    """Whether to skip this message in the transcript."""
    ambient: bool | None = None

skip_transcript class-attribute instance-attribute

skip_transcript: bool | None = None

Whether to skip this message in the transcript.

workflow_name class-attribute instance-attribute

workflow_name: str | None = None

meta.name from the workflow script (e.g. 'spec').

Only set when task_type is 'local_workflow'.

TaskStopOutput

Bases: TypedDict

tool_use_result for the TaskStop tool.

Source code in src/clawd_code_sdk/models/output_types.py
class TaskStopOutput(TypedDict):
    """``tool_use_result`` for the TaskStop tool."""

    message: str
    task_id: str
    task_type: str
    command: NotRequired[str]

TaskUpdatedSystemMessage

Bases: BaseSystemMessage

System message emitted when a subagent task was updated.

Source code in src/clawd_code_sdk/models/system_messages.py
class TaskUpdatedSystemMessage(BaseSystemMessage):
    """System message emitted when a subagent task was updated."""

    subtype: Literal["task_updated"] = "task_updated"
    task_id: str
    run_id: str | None = None
    patch: Patch

TeammateIdleHookInput

Bases: BaseHookInput

Input data for TeammateIdle hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class TeammateIdleHookInput(BaseHookInput):
    """Input data for TeammateIdle hook events."""

    hook_event_name: Literal["TeammateIdle"]
    teammate_name: str
    team_name: 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.

ThinkingTokensMessage

Bases: BaseSystemMessage

Running estimate of thinking tokens for the current turn.

Source code in src/clawd_code_sdk/models/system_messages.py
class ThinkingTokensMessage(BaseSystemMessage):
    """Running estimate of thinking tokens for the current turn."""

    subtype: Literal["thinking_tokens"] = "thinking_tokens"
    estimated_tokens: int
    estimated_tokens_delta: int
    user_message_uuid: str | None = None

TodoItem

Bases: TypedDict

A single todo item.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class TodoItem(TypedDict):
    """A single todo item."""

    content: str
    """The task description."""
    status: TaskStatus
    """The task status."""
    activeForm: str
    """Active form of the task description."""

activeForm instance-attribute

activeForm: str

Active form of the task description.

content instance-attribute

content: str

The task description.

status instance-attribute

status: TaskStatus

The task status.

TodoWriteInput

Bases: TypedDict

Input for the TodoWrite tool. Creates and manages a structured task list.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class TodoWriteInput(TypedDict):
    """Input for the TodoWrite tool. Creates and manages a structured task list."""

    todos: list[TodoItem]
    """The updated todo list."""

todos instance-attribute

todos: list[TodoItem]

The updated todo list.

TodoWriteOutput

Bases: TypedDict

tool_use_result for the TodoWrite tool.

Source code in src/clawd_code_sdk/models/output_types.py
class TodoWriteOutput(TypedDict):
    """``tool_use_result`` for the TodoWrite tool."""

    oldTodos: list[TodoItem]
    newTodos: list[TodoItem]

ToolConfig dataclass

Per-tool configuration for built-in tools.

Source code in src/clawd_code_sdk/models/options.py
@dataclass(kw_only=True)
class ToolConfig:
    """Per-tool configuration for built-in tools."""

    ask_user_question: AskUserQuestionToolConfig | None = None

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,
    )

ToolProgressMessage

Bases: BaseMessage

Progress update for a running tool.

Source code in src/clawd_code_sdk/models/messages.py
class ToolProgressMessage(BaseMessage):
    """Progress update for a running tool."""

    type: Literal["tool_progress"] = "tool_progress"
    session_id: str
    tool_use_id: str
    tool_name: str
    parent_tool_use_id: str | None
    elapsed_time_seconds: float
    task_id: str | None = None
    heartbeat: bool | None = None
    """Keep-alive tick with no new progress."""
    subagent_type: str | None = None
    subagent_retry: SubagentRetry | None = None

heartbeat class-attribute instance-attribute

heartbeat: bool | None = None

Keep-alive tick with no new progress.

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)

ToolUseMeta

Bases: ClaudeCodeBaseModel

Display metadata for a tool_use block in an assistant message (undocumented).

Source code in src/clawd_code_sdk/models/messages.py
class ToolUseMeta(ClaudeCodeBaseModel):
    """Display metadata for a tool_use block in an assistant message (undocumented)."""

    id: str
    """ID of the tool_use block this metadata belongs to."""
    tool_name: str
    """Name of the tool (without MCP server prefix)."""
    display_name: str | None = None
    """Human-readable tool name."""
    server_display_name: str | None = None
    """Display name of the MCP server providing the tool."""

display_name class-attribute instance-attribute

display_name: str | None = None

Human-readable tool name.

id instance-attribute

id: str

ID of the tool_use block this metadata belongs to.

server_display_name class-attribute instance-attribute

server_display_name: str | None = None

Display name of the MCP server providing the tool.

tool_name instance-attribute

tool_name: str

Name of the tool (without MCP server prefix).

ToolUseSummaryMessage

Bases: BaseMessage

Summary of preceding tool uses.

Source code in src/clawd_code_sdk/models/messages.py
class ToolUseSummaryMessage(BaseMessage):
    """Summary of preceding tool uses."""

    type: Literal["tool_use_summary"] = "tool_use_summary"
    session_id: str
    summary: str
    preceding_tool_use_ids: list[str]

ToolsPreset

Bases: TypedDict

Tools preset configuration.

Source code in src/clawd_code_sdk/models/agents.py
class ToolsPreset(TypedDict):
    """Tools preset configuration."""

    type: Literal["preset"]
    preset: Literal["claude_code"]

TriggerMetadata

Bases: TypedDict

Trigger metadata.

Source code in src/clawd_code_sdk/models/system_messages.py
class TriggerMetadata(TypedDict):
    """Trigger metadata."""

    trigger: CompactionTrigger
    pre_tokens: int
    post_tokens: NotRequired[int]
    duration_ms: NotRequired[float]
    preserved_segment: NotRequired[PreservedSegment]
    preserved_messages: NotRequired[PreservedMessages]

URLPDFSource

Bases: BaseContentBlock

PDF document referenced by URL.

Source code in src/clawd_code_sdk/models/content_blocks.py
class URLPDFSource(BaseContentBlock):
    """PDF document referenced by URL."""

    type: Literal["url"] = "url"
    url: str

Usage

Bases: BaseModel

Token usage counters.

Used both for per-turn snapshots (on ResultMessage) and as an accumulator (on ClaudeSDKClient.query_usage / session_usage).

Source code in src/clawd_code_sdk/models/usage.py
class Usage(BaseModel):
    """Token usage counters.

    Used both for per-turn snapshots (on ResultMessage) and as an accumulator
    (on ClaudeSDKClient.query_usage / session_usage).
    """

    input_tokens: int = 0
    """The number of input tokens which were used."""
    output_tokens: int = 0
    """The number of output tokens which were used."""
    cache_creation_input_tokens: int = 0
    """The number of input tokens used to create the cache entry."""
    cache_read_input_tokens: int = 0
    """The number of input tokens read from the cache."""
    cache_creation: CacheCreationUsage | None = None
    """Cache-write tokens split by TTL."""
    server_tool_use: AgentServerToolUse | None = None
    """Server-side tool usage counters."""
    output_tokens_details: OutputTokensDetails | None = None
    """Breakdown of output tokens."""
    service_tier: str | None = None
    """Service tier the request was served on (e.g. "standard")."""
    inference_geo: str | None = None
    """Inference geography (e.g. "global")."""
    speed: str | None = None
    """Speed mode (e.g. "standard", "fast")."""
    iterations: list[UsageIteration] | None = None
    """Per-iteration usage for the turn."""
    fallback_credit: Any = None
    """Fallback credit info (may be null)."""
    model_config = ConfigDict(extra="forbid" if IS_DEV else "ignore", use_attribute_docstrings=True)

    @property
    def total_tokens(self) -> int:
        """Sum of all token fields."""
        return (
            self.input_tokens
            + self.output_tokens
            + self.cache_creation_input_tokens
            + self.cache_read_input_tokens
        )

    def accumulate(self, usage: Usage) -> None:
        """Add another Usage's values to this one."""
        self.input_tokens += usage.input_tokens
        self.output_tokens += usage.output_tokens
        self.cache_creation_input_tokens += usage.cache_creation_input_tokens
        self.cache_read_input_tokens += usage.cache_read_input_tokens

    def reset(self) -> None:
        """Reset all counters to zero."""
        self.input_tokens = 0
        self.output_tokens = 0
        self.cache_creation_input_tokens = 0
        self.cache_read_input_tokens = 0

    def to_otel(self, *, partial: bool = False) -> dict[str, int]:
        """Extract usage metrics from a Claude usage object or dict.

        Args:
            usage: A usage object or dict from the SDK.
            partial: If True, prefix attribute names with ``gen_ai.usage.partial.``
                instead of ``gen_ai.usage.``. Used for chat spans where per-message
                usage from the SDK is unreliable.
        """
        prefix = "gen_ai.usage.partial." if partial else "gen_ai.usage."
        result: dict[str, int] = {}
        # input_tokens is the *total* input token count.
        # The Anthropic API's input_tokens only counts uncached tokens,
        # so we sum input + cache_read + cache_creation to get the actual total.
        input_tokens = self.input_tokens
        cache_read = self.cache_read_input_tokens
        cache_creation = self.cache_creation_input_tokens
        if total_input := (input_tokens + cache_read + cache_creation):
            result[f"{prefix}input_tokens"] = total_input

        result[f"{prefix}output_tokens"] = self.output_tokens

        if cache_read:
            result[f"{prefix}cache_read.input_tokens"] = cache_read
        if cache_creation:
            result[f"{prefix}cache_creation.input_tokens"] = cache_creation

        return result

cache_creation class-attribute instance-attribute

cache_creation: CacheCreationUsage | None = None

Cache-write tokens split by TTL.

cache_creation_input_tokens class-attribute instance-attribute

cache_creation_input_tokens: int = 0

The number of input tokens used to create the cache entry.

cache_read_input_tokens class-attribute instance-attribute

cache_read_input_tokens: int = 0

The number of input tokens read from the cache.

fallback_credit class-attribute instance-attribute

fallback_credit: Any = None

Fallback credit info (may be null).

inference_geo class-attribute instance-attribute

inference_geo: str | None = None

Inference geography (e.g. "global").

input_tokens class-attribute instance-attribute

input_tokens: int = 0

The number of input tokens which were used.

iterations class-attribute instance-attribute

iterations: list[UsageIteration] | None = None

Per-iteration usage for the turn.

output_tokens class-attribute instance-attribute

output_tokens: int = 0

The number of output tokens which were used.

output_tokens_details class-attribute instance-attribute

output_tokens_details: OutputTokensDetails | None = None

Breakdown of output tokens.

server_tool_use class-attribute instance-attribute

server_tool_use: AgentServerToolUse | None = None

Server-side tool usage counters.

service_tier class-attribute instance-attribute

service_tier: str | None = None

Service tier the request was served on (e.g. "standard").

speed class-attribute instance-attribute

speed: str | None = None

Speed mode (e.g. "standard", "fast").

total_tokens property

total_tokens: int

Sum of all token fields.

accumulate

accumulate(usage: Usage) -> None

Add another Usage's values to this one.

Source code in src/clawd_code_sdk/models/usage.py
def accumulate(self, usage: Usage) -> None:
    """Add another Usage's values to this one."""
    self.input_tokens += usage.input_tokens
    self.output_tokens += usage.output_tokens
    self.cache_creation_input_tokens += usage.cache_creation_input_tokens
    self.cache_read_input_tokens += usage.cache_read_input_tokens

reset

reset() -> None

Reset all counters to zero.

Source code in src/clawd_code_sdk/models/usage.py
def reset(self) -> None:
    """Reset all counters to zero."""
    self.input_tokens = 0
    self.output_tokens = 0
    self.cache_creation_input_tokens = 0
    self.cache_read_input_tokens = 0

to_otel

to_otel(*, partial: bool = False) -> dict[str, int]

Extract usage metrics from a Claude usage object or dict.

Parameters:

Name Type Description Default
usage

A usage object or dict from the SDK.

required
partial bool

If True, prefix attribute names with gen_ai.usage.partial. instead of gen_ai.usage.. Used for chat spans where per-message usage from the SDK is unreliable.

False
Source code in src/clawd_code_sdk/models/usage.py
def to_otel(self, *, partial: bool = False) -> dict[str, int]:
    """Extract usage metrics from a Claude usage object or dict.

    Args:
        usage: A usage object or dict from the SDK.
        partial: If True, prefix attribute names with ``gen_ai.usage.partial.``
            instead of ``gen_ai.usage.``. Used for chat spans where per-message
            usage from the SDK is unreliable.
    """
    prefix = "gen_ai.usage.partial." if partial else "gen_ai.usage."
    result: dict[str, int] = {}
    # input_tokens is the *total* input token count.
    # The Anthropic API's input_tokens only counts uncached tokens,
    # so we sum input + cache_read + cache_creation to get the actual total.
    input_tokens = self.input_tokens
    cache_read = self.cache_read_input_tokens
    cache_creation = self.cache_creation_input_tokens
    if total_input := (input_tokens + cache_read + cache_creation):
        result[f"{prefix}input_tokens"] = total_input

    result[f"{prefix}output_tokens"] = self.output_tokens

    if cache_read:
        result[f"{prefix}cache_read.input_tokens"] = cache_read
    if cache_creation:
        result[f"{prefix}cache_creation.input_tokens"] = cache_creation

    return result

UsageMoney

Bases: ClaudeCodeBaseModel

An amount in minor units (amount_minor / 10**exponent in currency).

Source code in src/clawd_code_sdk/models/context_usage.py
class UsageMoney(ClaudeCodeBaseModel):
    """An amount in minor units (amount_minor / 10**exponent in currency)."""

    model_config = ConfigDict(extra="ignore")

    amount_minor: int
    currency: str
    exponent: int

    @property
    def amount(self) -> float:
        """The amount in major units (e.g. dollars)."""
        return self.amount_minor / 10**self.exponent

amount property

amount: float

The amount in major units (e.g. dollars).

UsageRateLimits

Bases: ClaudeCodeBaseModel

Plan rate-limit windows from the claude.ai usage endpoint.

Only the fields documented by the TypeScript SDK are modelled; the endpoint carries many experimental extras, which are ignored.

Source code in src/clawd_code_sdk/models/context_usage.py
class UsageRateLimits(ClaudeCodeBaseModel):
    """Plan rate-limit windows from the claude.ai usage endpoint.

    Only the fields documented by the TypeScript SDK are modelled; the endpoint carries
    many experimental extras, which are ignored.
    """

    model_config = ConfigDict(extra="ignore")

    five_hour: UsageWindow | None = None
    seven_day: UsageWindow | None = None
    seven_day_oauth_apps: UsageWindow | None = None
    seven_day_opus: UsageWindow | None = None
    seven_day_sonnet: UsageWindow | None = None
    model_scoped: list[ModelScopedUsageWindow] | None = None
    """Per-model weekly windows (absent when unknown, empty when there are none)."""
    extra_usage: UsageReportExtraUsage | None = None
    limits: list[UsageReportLimit] | None = None
    """The server's usage rows, in the server's order (render verbatim)."""
    spend: UsageSpend | None = None
    """Usage-credit spend (not documented by the TypeScript SDK; may change)."""

limits class-attribute instance-attribute

limits: list[UsageReportLimit] | None = None

The server's usage rows, in the server's order (render verbatim).

model_scoped class-attribute instance-attribute

model_scoped: list[ModelScopedUsageWindow] | None = None

Per-model weekly windows (absent when unknown, empty when there are none).

spend class-attribute instance-attribute

spend: UsageSpend | None = None

Usage-credit spend (not documented by the TypeScript SDK; may change).

UsageSpend

Bases: ClaudeCodeBaseModel

Usage-credit spend beyond the plan windows (undocumented, server-defined).

Source code in src/clawd_code_sdk/models/context_usage.py
class UsageSpend(ClaudeCodeBaseModel):
    """Usage-credit spend beyond the plan windows (undocumented, server-defined)."""

    model_config = ConfigDict(extra="ignore")

    enabled: bool = False
    used: UsageMoney | None = None
    limit: UsageMoney | None = None
    percent: float | None = None
    """Share of the spend limit used, 0-100."""
    severity: str | None = None

percent class-attribute instance-attribute

percent: float | None = None

Share of the spend limit used, 0-100.

UsageWindow

Bases: ClaudeCodeBaseModel

Utilization of one plan rate-limit window.

Source code in src/clawd_code_sdk/models/context_usage.py
class UsageWindow(ClaudeCodeBaseModel):
    """Utilization of one plan rate-limit window."""

    model_config = ConfigDict(extra="ignore")  # server-defined, see UsageReportExtraUsage

    utilization: float | None
    """Percentage of the window used, 0-100."""
    resets_at: str | None
    """ISO 8601 timestamp of the window's reset."""

resets_at instance-attribute

resets_at: str | None

ISO 8601 timestamp of the window's reset.

utilization instance-attribute

utilization: float | None

Percentage of the window used, 0-100.

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}
    )

UserFilePrompt dataclass

A user prompt referencing a file uploaded via the Anthropic Files API.

Source code in src/clawd_code_sdk/models/prompts.py
@dataclass
class UserFilePrompt:
    """A user prompt referencing a file uploaded via the Anthropic Files API."""

    file_id: str
    """Anthropic file identifier (e.g. 'file_abc123')."""
    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=BetaFileDocumentSourceParam(type="file", file_id=self.file_id),
            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.

file_id instance-attribute

file_id: str

Anthropic file identifier (e.g. 'file_abc123').

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=BetaFileDocumentSourceParam(type="file", file_id=self.file_id),
        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}
    )

UserPromptExpansionHookInput

Bases: BaseHookInput

Input data for UserPromptExpansion hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class UserPromptExpansionHookInput(BaseHookInput):
    """Input data for UserPromptExpansion hook events."""

    hook_event_name: Literal["UserPromptExpansion"]
    expansion_type: Literal["slash_command", "mcp_prompt"]
    command_name: str
    command_args: str
    command_source: NotRequired[str]
    prompt: str

UserPromptExpansionHookSpecificOutput

Bases: TypedDict

Hook-specific output for UserPromptExpansion events.

Source code in src/clawd_code_sdk/models/hooks.py
class UserPromptExpansionHookSpecificOutput(TypedDict):
    """Hook-specific output for UserPromptExpansion events."""

    hookEventName: Literal["UserPromptExpansion"]
    additionalContext: NotRequired[str]

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]

UserPromptSubmitHookSpecificOutput

Bases: TypedDict

Hook-specific output for UserPromptSubmit events.

Source code in src/clawd_code_sdk/models/hooks.py
class UserPromptSubmitHookSpecificOutput(TypedDict):
    """Hook-specific output for UserPromptSubmit events."""

    hookEventName: Literal["UserPromptSubmit"]
    additionalContext: NotRequired[str]
    sessionTitle: NotRequired[str]
    suppressOriginalPrompt: NotRequired[bool]
    """When decision is "block", omit the original prompt from the block message."""

suppressOriginalPrompt instance-attribute

suppressOriginalPrompt: NotRequired[bool]

When decision is "block", omit the original prompt from the block message.

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)

WebFetchInput

Bases: TypedDict

Input for the WebFetch tool. Fetches content from a URL and processes it with AI.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class WebFetchInput(TypedDict):
    """Input for the WebFetch tool. Fetches content from a URL and processes it with AI."""

    url: str
    """The URL to fetch content from."""
    prompt: str
    """The prompt to run on the fetched content."""
    offset: NotRequired[int]
    """Character position in the page text to start reading from."""

offset instance-attribute

offset: NotRequired[int]

Character position in the page text to start reading from.

prompt instance-attribute

prompt: str

The prompt to run on the fetched content.

url instance-attribute

url: str

The URL to fetch content from.

WebFetchOutput

Bases: TypedDict

tool_use_result for the WebFetch tool.

Source code in src/clawd_code_sdk/models/output_types.py
class WebFetchOutput(TypedDict):
    """``tool_use_result`` for the WebFetch tool."""

    bytes: int
    """Size of the fetched content in bytes."""
    code: int
    """HTTP response code."""
    codeText: str
    """HTTP response code text."""
    result: str
    """Processed result from applying the prompt to the content."""
    durationMs: int
    url: str
    artifactRead: NotRequired[ArtifactReadMarker]
    """Set when the fetched URL is an artifact that now counts as viewed."""

artifactRead instance-attribute

artifactRead: NotRequired[ArtifactReadMarker]

Set when the fetched URL is an artifact that now counts as viewed.

bytes instance-attribute

bytes: int

Size of the fetched content in bytes.

code instance-attribute

code: int

HTTP response code.

codeText instance-attribute

codeText: str

HTTP response code text.

result instance-attribute

result: str

Processed result from applying the prompt to the content.

WebSearchHit

Bases: TypedDict

A single search result hit.

Source code in src/clawd_code_sdk/models/output_types.py
class WebSearchHit(TypedDict):
    """A single search result hit."""

    title: str
    url: str
    snippet: NotRequired[str]
    """Snippet of the search hit."""

snippet instance-attribute

snippet: NotRequired[str]

Snippet of the search hit.

WebSearchInput

Bases: TypedDict

Input for the WebSearch tool. Searches the web and returns formatted results.

Source code in src/clawd_code_sdk/models/input_types.py
@_extra_allow
class WebSearchInput(TypedDict):
    """Input for the WebSearch tool. Searches the web and returns formatted results."""

    query: str
    """The search query to use."""
    allowed_domains: NotRequired[list[str]]
    """Only include results from these domains."""
    blocked_domains: NotRequired[list[str]]
    """Never include results from these domains."""

allowed_domains instance-attribute

allowed_domains: NotRequired[list[str]]

Only include results from these domains.

blocked_domains instance-attribute

blocked_domains: NotRequired[list[str]]

Never include results from these domains.

query instance-attribute

query: str

The search query to use.

WebSearchOutput

Bases: TypedDict

tool_use_result for the WebSearch tool.

Source code in src/clawd_code_sdk/models/output_types.py
class WebSearchOutput(TypedDict):
    """``tool_use_result`` for the WebSearch tool."""

    query: str
    results: list[WebSearchToolResult | str]
    """Search results and/or text commentary from the model."""
    durationSeconds: float
    searchCount: NotRequired[int]
    """Number of searches performed."""

results instance-attribute

results: list[WebSearchToolResult | str]

Search results and/or text commentary from the model.

searchCount instance-attribute

searchCount: NotRequired[int]

Number of searches performed.

WebSearchToolResult

Bases: TypedDict

A structured search result entry.

Source code in src/clawd_code_sdk/models/output_types.py
class WebSearchToolResult(TypedDict):
    """A structured search result entry."""

    tool_use_id: str
    content: list[WebSearchHit]

WorkerShuttingDownMessage

Bases: BaseSystemMessage

Emitted when the CLI worker is shutting down.

Source code in src/clawd_code_sdk/models/system_messages.py
class WorkerShuttingDownMessage(BaseSystemMessage):
    """Emitted when the CLI worker is shutting down."""

    subtype: Literal["worker_shutting_down"] = "worker_shutting_down"
    reason: str

WorktreeCreateHookInput

Bases: BaseHookInput

Input data for WorktreeCreate hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class WorktreeCreateHookInput(BaseHookInput):
    """Input data for WorktreeCreate hook events."""

    hook_event_name: Literal["WorktreeCreate"]
    name: str

WorktreeCreateHookSpecificOutput

Bases: TypedDict

Hook-specific output for WorktreeCreate events.

Source code in src/clawd_code_sdk/models/hooks.py
class WorktreeCreateHookSpecificOutput(TypedDict):
    """Hook-specific output for WorktreeCreate events."""

    hookEventName: Literal["WorktreeCreate"]
    worktreePath: str

WorktreeRemoveHookInput

Bases: BaseHookInput

Input data for WorktreeRemove hook events.

Source code in src/clawd_code_sdk/models/hooks.py
class WorktreeRemoveHookInput(BaseHookInput):
    """Input data for WorktreeRemove hook events."""

    hook_event_name: Literal["WorktreeRemove"]
    worktree_path: str

WriteOutput

Bases: TypedDict

tool_use_result for the Write tool.

Source code in src/clawd_code_sdk/models/output_types.py
class WriteOutput(TypedDict):
    """``tool_use_result`` for the Write tool."""

    type: Literal["create", "update"]
    filePath: str
    content: str
    structuredPatch: list[StructuredPatchHunk]
    originalFile: str | None
    gitDiff: NotRequired[GitDiff]
    userModified: NotRequired[bool]
    staged: NotRequired[bool]
    """Whether the write was staged instead of written."""

staged instance-attribute

staged: NotRequired[bool]

Whether the write was staged instead of written.