18 The SDK bundles a native Claude Code binary for your platform as an optional dependency such as `@anthropic-ai/claude-agent-sdk-darwin-arm64`. You don't need to install Claude Code separately. If your package manager skips optional dependencies, the SDK throws `Native CLI binary for <platform> not found`; set [`pathToClaudeCodeExecutable`](#options) to a separately installed `claude` binary instead.18 The SDK bundles a native Claude Code binary for your platform as an optional dependency such as `@anthropic-ai/claude-agent-sdk-darwin-arm64`. You don't need to install Claude Code separately. If your package manager skips optional dependencies, the SDK throws `Native CLI binary for <platform> not found`; set [`pathToClaudeCodeExecutable`](#options) to a separately installed `claude` binary instead.
19</Note>19</Note>
20 20
21### Compile to a single executable
22
23When you compile your application into a single-file executable with `bun build --compile`, the SDK cannot resolve the bundled CLI binary at runtime. `require.resolve` does not work inside the compiled executable's `$bunfs` virtual filesystem, so the SDK throws `Native CLI binary for <platform> not found`.
24
25To work around this, embed the platform binary as a file asset, extract it to a real path at startup with `extractFromBunfs()`, and pass that path to [`pathToClaudeCodeExecutable`](#options).
26
27The `extractFromBunfs()` helper requires `@anthropic-ai/claude-agent-sdk` v0.3.144 or later. The example below builds for macOS on Apple Silicon:
28
29```typescript theme={null}
30import binPath from "@anthropic-ai/claude-agent-sdk-darwin-arm64/claude" with { type: "file" };
31import { extractFromBunfs } from "@anthropic-ai/claude-agent-sdk/extract";
32import { query } from "@anthropic-ai/claude-agent-sdk";
33
34const cliPath = extractFromBunfs(binPath);
35
36for await (const message of query({
37 prompt: "Hello",
38 options: { pathToClaudeCodeExecutable: cliPath },
39})) {
40 console.log(message);
41}
42```
43
44`extractFromBunfs()` copies the embedded binary out of the compiled executable's virtual filesystem to a per-user temp directory and returns the real path. Outside a compiled executable it returns the input path unchanged, so the same code runs in development without modification.
45
46Each compiled executable embeds a single platform's binary. Match the platform package in the import to your `--target`:
47
48* To cross-compile, install the non-matching platform package, for example `npm install @anthropic-ai/claude-agent-sdk-linux-x64 --force`.
49* On Windows, the binary subpath is `claude.exe`, for example `@anthropic-ai/claude-agent-sdk-win32-x64/claude.exe`.
50
21## Functions51## Functions
22 52
23### `query()`53### `query()`
222#### Return type: `SessionMessage`252#### Return type: `SessionMessage`
223 253
224| Property | Type | Description |254| Property | Type | Description |
225| :------------------- | :---------------------- | :-------------------------------------- |255| :------------------- | :---------------------- | :------------------------------------------------------------------------------------------------------------------------------ |
226| `type` | `"user" \| "assistant"` | Message role |256| `type` | `"user" \| "assistant"` | Message role |
227| `uuid` | `string` | Unique message identifier |257| `uuid` | `string` | Unique message identifier |
228| `session_id` | `string` | Session this message belongs to |258| `session_id` | `string` | Session this message belongs to |
229| `message` | `unknown` | Raw message payload from the transcript |259| `message` | `unknown` | Raw message payload from the transcript |
230| `parent_tool_use_id` | `null` | Reserved |260| `parent_tool_use_id` | `string \| null` | For subagent messages, the `tool_use_id` of the spawning `Agent` tool call. `null` for main-session messages and older sessions |
231 261
232#### Example262#### Example
233 263
371| `additionalDirectories` | `string[]` | `[]` | Additional directories Claude can access |401| `additionalDirectories` | `string[]` | `[]` | Additional directories Claude can access |
372| `agent` | `string` | `undefined` | Agent name for the main thread. The agent must be defined in the `agents` option or in settings |402| `agent` | `string` | `undefined` | Agent name for the main thread. The agent must be defined in the `agents` option or in settings |
373| `agents` | `Record<string, [`AgentDefinition`](#agentdefinition)>` | `undefined` | Programmatically define subagents |403| `agents` | `Record<string, [`AgentDefinition`](#agentdefinition)>` | `undefined` | Programmatically define subagents |
404| `agentProgressSummaries` | `boolean` | `false` | When `true`, generate one-line progress summaries for subagents and forward them on [`task_progress`](#sdktaskprogressmessage) events via the `summary` field. Applies to foreground and background subagents |
374| `allowDangerouslySkipPermissions` | `boolean` | `false` | Enable bypassing permissions. Required when using `permissionMode: 'bypassPermissions'` |405| `allowDangerouslySkipPermissions` | `boolean` | `false` | Enable bypassing permissions. Required when using `permissionMode: 'bypassPermissions'` |
375| `allowedTools` | `string[]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permissionMode` and `canUseTool`. Use `disallowedTools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |406| `allowedTools` | `string[]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permissionMode` and `canUseTool`. Use `disallowedTools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |
376| `betas` | [`SdkBeta`](#sdkbeta)`[]` | `[]` | Enable beta features |407| `betas` | [`SdkBeta`](#sdkbeta)`[]` | `[]` | Enable beta features |
379| `cwd` | `string` | `process.cwd()` | Current working directory |410| `cwd` | `string` | `process.cwd()` | Current working directory |
380| `debug` | `boolean` | `false` | Enable debug mode for the Claude Code process |411| `debug` | `boolean` | `false` | Enable debug mode for the Claude Code process |
381| `debugFile` | `string` | `undefined` | Write debug logs to a specific file path. Implicitly enables debug mode |412| `debugFile` | `string` | `undefined` | Write debug logs to a specific file path. Implicitly enables debug mode |
382| `disallowedTools` | `string[]` | `[]` | Tools to always deny. Deny rules are checked first and override `allowedTools` and `permissionMode` (including `bypassPermissions`) |413| `disallowedTools` | `string[]` | `[]` | Tools to deny. A bare name such as `"Bash"` removes the tool from Claude's context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |
383| `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'` | `'high'` | Controls how much effort Claude puts into its response. Works with adaptive thinking to guide thinking depth |414| `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'` | `'high'` | Controls how much effort Claude puts into its response. Works with adaptive thinking to guide thinking depth |
384| `enableFileCheckpointing` | `boolean` | `false` | Enable file change tracking for rewinding. See [File checkpointing](/en/agent-sdk/file-checkpointing) |415| `enableFileCheckpointing` | `boolean` | `false` | Enable file change tracking for rewinding. See [File checkpointing](/en/agent-sdk/file-checkpointing) |
385| `env` | `Record<string, string \| undefined>` | `process.env` | Environment variables. See [Environment variables](/en/env-vars) for variables the underlying CLI reads, and [Handle slow or stalled API responses](#handle-slow-or-stalled-api-responses) for timeout-related variables. Set `CLAUDE_AGENT_SDK_CLIENT_APP` to identify your app in the User-Agent header |416| `env` | `Record<string, string \| undefined>` | `process.env` | Environment variables. See [Environment variables](/en/env-vars) for variables the underlying CLI reads, and [Handle slow or stalled API responses](#handle-slow-or-stalled-api-responses) for timeout-related variables. Set `CLAUDE_AGENT_SDK_CLIENT_APP` to identify your app in the User-Agent header |
388| `extraArgs` | `Record<string, string \| null>` | `{}` | Additional arguments |419| `extraArgs` | `Record<string, string \| null>` | `{}` | Additional arguments |
389| `fallbackModel` | `string` | `undefined` | Model to use if primary fails |420| `fallbackModel` | `string` | `undefined` | Model to use if primary fails |
390| `forkSession` | `boolean` | `false` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |421| `forkSession` | `boolean` | `false` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |
422| `forwardSubagentText` | `boolean` | `false` | Forward subagent text and thinking blocks as assistant and user messages with `parent_tool_use_id` set, so consumers can render a nested transcript. By default only `tool_use` and `tool_result` blocks from subagents are emitted |
391| `hooks` | `Partial<Record<`[`HookEvent`](#hookevent)`, `[`HookCallbackMatcher`](#hookcallbackmatcher)`[]>>` | `{}` | Hook callbacks for events |423| `hooks` | `Partial<Record<`[`HookEvent`](#hookevent)`, `[`HookCallbackMatcher`](#hookcallbackmatcher)`[]>>` | `{}` | Hook callbacks for events |
392| `includeHookEvents` | `boolean` | `false` | Include hook lifecycle events in the message stream as [`SDKHookStartedMessage`](#sdkhookstartedmessage), [`SDKHookProgressMessage`](#sdkhookprogressmessage), and [`SDKHookResponseMessage`](#sdkhookresponsemessage) |424| `includeHookEvents` | `boolean` | `false` | Include hook lifecycle events in the message stream as [`SDKHookStartedMessage`](#sdkhookstartedmessage), [`SDKHookProgressMessage`](#sdkhookprogressmessage), and [`SDKHookResponseMessage`](#sdkhookresponsemessage) |
393| `includePartialMessages` | `boolean` | `false` | Include partial message events |425| `includePartialMessages` | `boolean` | `false` | Include partial message events |
426| `loadTimeoutMs` | `number` | `60000` | *Alpha.* Timeout in milliseconds for each `sessionStore.load()` and `sessionStore.listSubkeys()` call during resume materialization. If the adapter doesn't settle within this window, the query fails instead of hanging. Ignored when `sessionStore` is not set |
427| `managedSettings` | `Settings` | `undefined` | Policy-tier settings supplied by the spawning parent process. Dropped when an IT-controlled managed-settings tier already exists on the machine, unless that admin opts in with `parentSettingsBehavior: 'merge'`. Filtered to restrictive-only keys regardless |
394| `maxBudgetUsd` | `number` | `undefined` | Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](/en/agent-sdk/cost-tracking) for accuracy caveats |428| `maxBudgetUsd` | `number` | `undefined` | Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](/en/agent-sdk/cost-tracking) for accuracy caveats |
395| `maxThinkingTokens` | `number` | `undefined` | *Deprecated:* Use `thinking` instead. Maximum tokens for thinking process |429| `maxThinkingTokens` | `number` | `undefined` | *Deprecated:* Use `thinking` instead. Maximum tokens for thinking process |
396| `maxTurns` | `number` | `undefined` | Maximum agentic turns (tool-use round trips) |430| `maxTurns` | `number` | `undefined` | Maximum agentic turns (tool-use round trips) |
397| `mcpServers` | `Record<string, [`McpServerConfig`](#mcpserverconfig)>` | `{}` | MCP server configurations |431| `mcpServers` | `Record<string, [`McpServerConfig`](#mcpserverconfig)>` | `{}` | MCP server configurations |
398| `model` | `string` | Default from CLI | Claude model to use |432| `model` | `string` | Default from CLI | Claude model to use |
433| `onElicitation` | `(request: ElicitationRequest, options: { signal: AbortSignal }) => Promise<ElicitationResult>` | `undefined` | Callback for handling MCP elicitation requests. Called when an MCP server requests user input and no hook handles it first. When not provided, unhandled elicitation requests are declined automatically |
399| `outputFormat` | `{ type: 'json_schema', schema: JSONSchema }` | `undefined` | Define output format for agent results. See [Structured outputs](/en/agent-sdk/structured-outputs) for details |434| `outputFormat` | `{ type: 'json_schema', schema: JSONSchema }` | `undefined` | Define output format for agent results. See [Structured outputs](/en/agent-sdk/structured-outputs) for details |
400| `outputStyle` | `string` | `undefined` | Name of an [output style](/en/output-styles) to activate for the session. The style must exist in a loaded `settingSources` location, such as `.claude/output-styles/`. See [Activate an output style](/en/agent-sdk/modifying-system-prompts#activate-an-output-style) |435| `outputStyle` | `string` | `undefined` | Not an `Options` field. Set `outputStyle` in the inline [`settings`](/en/settings) object or a settings file instead. See [Activate an output style](/en/agent-sdk/modifying-system-prompts#activate-an-output-style) |
401| `pathToClaudeCodeExecutable` | `string` | Auto-resolved from bundled native binary | Path to Claude Code executable. Only needed if optional dependencies were skipped during install or your platform isn't in the supported set |436| `pathToClaudeCodeExecutable` | `string` | Auto-resolved from bundled native binary | Path to Claude Code executable. Only needed if optional dependencies were skipped during install or your platform isn't in the supported set |
402| `permissionMode` | [`PermissionMode`](#permissionmode) | `'default'` | Permission mode for the session |437| `permissionMode` | [`PermissionMode`](#permissionmode) | `'default'` | Permission mode for the session |
403| `permissionPromptToolName` | `string` | `undefined` | MCP tool name for permission prompts |438| `permissionPromptToolName` | `string` | `undefined` | MCP tool name for permission prompts |
404| `persistSession` | `boolean` | `true` | When `false`, disables session persistence to disk. Sessions cannot be resumed later |439| `persistSession` | `boolean` | `true` | When `false`, disables session persistence to disk. Sessions cannot be resumed later |
440| `planModeInstructions` | `string` | `undefined` | Custom workflow instructions for plan mode. When `permissionMode` is `'plan'`, this string replaces the default plan-mode workflow body. The CLI still wraps it with the read-only enforcement preamble and the ExitPlanMode protocol footer |
405| `plugins` | [`SdkPluginConfig`](#sdkpluginconfig)`[]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |441| `plugins` | [`SdkPluginConfig`](#sdkpluginconfig)`[]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |
406| `promptSuggestions` | `boolean` | `false` | Enable prompt suggestions. Emits a `prompt_suggestion` message after each turn with a predicted next user prompt |442| `promptSuggestions` | `boolean` | `false` | Enable prompt suggestions. Emits a `prompt_suggestion` message after each turn with a predicted next user prompt |
407| `resume` | `string` | `undefined` | Session ID to resume |443| `resume` | `string` | `undefined` | Session ID to resume |
409| `sandbox` | [`SandboxSettings`](#sandboxsettings) | `undefined` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandboxsettings) for details |445| `sandbox` | [`SandboxSettings`](#sandboxsettings) | `undefined` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandboxsettings) for details |
410| `sessionId` | `string` | Auto-generated | Use a specific UUID for the session instead of auto-generating one |446| `sessionId` | `string` | Auto-generated | Use a specific UUID for the session instead of auto-generating one |
411| `sessionStore` | [`SessionStore`](/en/agent-sdk/session-storage#the-sessionstore-interface) | `undefined` | Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](/en/agent-sdk/session-storage) |447| `sessionStore` | [`SessionStore`](/en/agent-sdk/session-storage#the-sessionstore-interface) | `undefined` | Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](/en/agent-sdk/session-storage) |
448| `sessionStoreFlush` | `'batched' \| 'eager'` | `'batched'` | *Alpha.* Flush mode for `sessionStore`. Ignored when `sessionStore` is not set |
412| `settings` | `string \| Settings` | `undefined` | Inline [settings](/en/settings) object or path to a settings file. Populates the flag-settings layer in the [precedence order](/en/settings#settings-precedence). Change at runtime with [`applyFlagSettings()`](#applyflagsettings) |449| `settings` | `string \| Settings` | `undefined` | Inline [settings](/en/settings) object or path to a settings file. Populates the flag-settings layer in the [precedence order](/en/settings#settings-precedence). Change at runtime with [`applyFlagSettings()`](#applyflagsettings) |
413| `settingSources` | [`SettingSource`](#settingsource)`[]` | CLI defaults (all sources) | Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) |450| `settingSources` | [`SettingSource`](#settingsource)`[]` | CLI defaults (all sources) | Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) |
414| `skills` | `string[] \| 'all'` | `undefined` | Skills available to the session. Pass `'all'` to enable every discovered skill, or a list of skill names. When set, the SDK enables the Skill tool automatically without listing it in `allowedTools`. See [Skills](/en/agent-sdk/skills) |451| `skills` | `string[] \| 'all'` | `undefined` | Skills available to the session. Pass `'all'` to enable every discovered skill, or a list of skill names. When set, the SDK enables the Skill tool automatically without listing it in `allowedTools`. See [Skills](/en/agent-sdk/skills) |
416| `stderr` | `(data: string) => void` | `undefined` | Callback for stderr output |453| `stderr` | `(data: string) => void` | `undefined` | Callback for stderr output |
417| `strictMcpConfig` | `boolean` | `false` | Use only the servers passed in `mcpServers` and ignore project `.mcp.json`, user settings, and plugin-provided MCP servers |454| `strictMcpConfig` | `boolean` | `false` | Use only the servers passed in `mcpServers` and ignore project `.mcp.json`, user settings, and plugin-provided MCP servers |
418| `systemPrompt` | `string \| { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean }` | `undefined` (minimal prompt) | System prompt configuration. Pass a string for custom prompt, or `{ type: 'preset', preset: 'claude_code' }` to use Claude Code's system prompt. When using the preset object form, add `append` to extend it with additional instructions, and set `excludeDynamicSections: true` to move per-session context into the first user message for [better prompt-cache reuse across machines](/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) |455| `systemPrompt` | `string \| { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean }` | `undefined` (minimal prompt) | System prompt configuration. Pass a string for custom prompt, or `{ type: 'preset', preset: 'claude_code' }` to use Claude Code's system prompt. When using the preset object form, add `append` to extend it with additional instructions, and set `excludeDynamicSections: true` to move per-session context into the first user message for [better prompt-cache reuse across machines](/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) |
456| `taskBudget` | `{ total: number }` | `undefined` | *Alpha.* API-side task budget in tokens. When set, the model is told its remaining token budget so it can pace tool use and wrap up before the limit |
419| `thinking` | [`ThinkingConfig`](#thinkingconfig) | `{ type: 'adaptive' }` for supported models | Controls Claude's thinking/reasoning behavior. See [`ThinkingConfig`](#thinkingconfig) for options |457| `thinking` | [`ThinkingConfig`](#thinkingconfig) | `{ type: 'adaptive' }` for supported models | Controls Claude's thinking/reasoning behavior. See [`ThinkingConfig`](#thinkingconfig) for options |
458| `title` | `string` | `undefined` | Display title for the session. When resuming via `resume` or `continue`, the resumed session's persisted title takes precedence; use [`renameSession()`](#renamesession) to retitle an existing session |
459| `toolAliases` | `Record<string, string>` | `undefined` | Map built-in tool names to MCP tool names so Claude calls your MCP implementation in place of the built-in. For example, `{ Bash: 'mcp__workspace__bash' }` |
420| `toolConfig` | [`ToolConfig`](#toolconfig) | `undefined` | Configuration for built-in tool behavior. See [`ToolConfig`](#toolconfig) for details |460| `toolConfig` | [`ToolConfig`](#toolconfig) | `undefined` | Configuration for built-in tool behavior. See [`ToolConfig`](#toolconfig) for details |
421| `tools` | `string[] \| { type: 'preset'; preset: 'claude_code' }` | `undefined` | Tool configuration. Pass an array of tool names or use the preset to get Claude Code's default tools |461| `tools` | `string[] \| { type: 'preset'; preset: 'claude_code' }` | `undefined` | Tool configuration. Pass an array of tool names or use the preset to get Claude Code's default tools |
422 462
914 | SDKTaskStartedMessage954 | SDKTaskStartedMessage
915 | SDKTaskProgressMessage955 | SDKTaskProgressMessage
916 | SDKTaskUpdatedMessage956 | SDKTaskUpdatedMessage
957 | SDKSessionStateChangedMessage
958 | SDKNotificationMessage
917 | SDKFilesPersistedEvent959 | SDKFilesPersistedEvent
918 | SDKToolUseSummaryMessage960 | SDKToolUseSummaryMessage
961 | SDKMemoryRecallMessage
919 | SDKRateLimitEvent962 | SDKRateLimitEvent
963 | SDKElicitationCompleteMessage
920 | SDKPermissionDeniedMessage964 | SDKPermissionDeniedMessage
921 | SDKPromptSuggestionMessage;965 | SDKPromptSuggestionMessage
966 | SDKAPIRetryMessage
967 | SDKMirrorErrorMessage;
922```968```
923 969
924### `SDKAssistantMessage`970### `SDKAssistantMessage`
938 984
939The `message` field is a [`BetaMessage`](https://platform.claude.com/docs/en/api/messages/create) from the Anthropic SDK. It includes fields like `id`, `content`, `model`, `stop_reason`, and `usage`.985The `message` field is a [`BetaMessage`](https://platform.claude.com/docs/en/api/messages/create) from the Anthropic SDK. It includes fields like `id`, `content`, `model`, `stop_reason`, and `usage`.
940 986
941`SDKAssistantMessageError` is one of: `'authentication_failed'`, `'oauth_org_not_allowed'`, `'billing_error'`, `'rate_limit'`, `'invalid_request'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`.987`SDKAssistantMessageError` is one of: `'authentication_failed'`, `'oauth_org_not_allowed'`, `'billing_error'`, `'rate_limit'`, `'invalid_request'`, `'model_not_found'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`. `'model_not_found'` means the selected model doesn't exist or isn't available to your account or deployment.
942 988
943### `SDKUserMessage`989### `SDKUserMessage`
944 990
992 duration_ms: number;1038 duration_ms: number;
993 duration_api_ms: number;1039 duration_api_ms: number;
994 is_error: boolean;1040 is_error: boolean;
1041 api_error_status?: number | null;
995 num_turns: number;1042 num_turns: number;
996 result: string;1043 result: string;
997 stop_reason: string | null;1044 stop_reason: string | null;
1045 ttft_ms?: number;
998 total_cost_usd: number;1046 total_cost_usd: number;
999 usage: NonNullableUsage;1047 usage: NonNullableUsage;
1000 modelUsage: { [modelName: string]: ModelUsage };1048 modelUsage: { [modelName: string]: ModelUsage };
1001 permission_denials: SDKPermissionDenial[];1049 permission_denials: SDKPermissionDenial[];
1002 structured_output?: unknown;1050 structured_output?: unknown;
1003 deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> };1051 deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> };
1052 terminal_reason?: TerminalReason;
1053 fast_mode_state?: FastModeState;
1004 origin?: SDKMessageOrigin;1054 origin?: SDKMessageOrigin;
1005 }1055 }
1006 | {1056 | {
1022 modelUsage: { [modelName: string]: ModelUsage };1072 modelUsage: { [modelName: string]: ModelUsage };
1023 permission_denials: SDKPermissionDenial[];1073 permission_denials: SDKPermissionDenial[];
1024 errors: string[];1074 errors: string[];
1075 terminal_reason?: TerminalReason;
1076 fast_mode_state?: FastModeState;
1025 origin?: SDKMessageOrigin;1077 origin?: SDKMessageOrigin;
1026 };1078 };
1027```1079```
1028 1080
1081Several fields on the result carry diagnostic detail beyond `subtype`:
1082
1083* `api_error_status`: the HTTP status code of the API error that terminated the conversation. Absent or `null` when the turn ended without an API error.
1084* `ttft_ms`: time to first token in milliseconds. Present on the success arm only.
1085* `terminal_reason`: why the loop ended. One of `"completed"`, `"max_turns"`, `"tool_deferred"`, `"aborted_streaming"`, `"aborted_tools"`, `"hook_stopped"`, `"stop_hook_prevented"`, `"blocking_limit"`, `"rapid_refill_breaker"`, `"prompt_too_long"`, `"image_error"`, or `"model_error"`.
1086* `fast_mode_state`: one of `"on"`, `"off"`, or `"cooldown"`.
1087
1029The `origin` field forwards the [`SDKMessageOrigin`](#sdkmessageorigin) of the user message that triggered this result. When a background task finishes and the SDK injects a synthetic follow-up turn, the resulting `SDKResultMessage` carries `origin: { kind: "task-notification" }`. Check this field to distinguish results that answer your prompt from results emitted for background-task follow-ups, so you can route or suppress the latter. The field is absent for results emitted before any user turn, such as startup errors.1088The `origin` field forwards the [`SDKMessageOrigin`](#sdkmessageorigin) of the user message that triggered this result. When a background task finishes and the SDK injects a synthetic follow-up turn, the resulting `SDKResultMessage` carries `origin: { kind: "task-notification" }`. Check this field to distinguish results that answer your prompt from results emitted for background-task follow-ups, so you can route or suppress the latter. The field is absent for results emitted before any user turn, such as startup errors.
1030 1089
1031When a `PreToolUse` hook returns `permissionDecision: "defer"`, the result has `stop_reason: "tool_deferred"` and `deferred_tool_use` carries the pending tool's `id`, `name`, and `input`. Read this field to surface the request in your own UI, then resume with the same `session_id` to continue. See [Defer a tool call for later](/en/hooks#defer-a-tool-call-for-later) for the full round trip.1090When a `PreToolUse` hook returns `permissionDecision: "defer"`, the result has `stop_reason: "tool_deferred"` and `deferred_tool_use` carries the pending tool's `id`, `name`, and `input`. Read this field to surface the request in your own UI, then resume with the same `session_id` to continue. See [Defer a tool call for later](/en/hooks#defer-a-tool-call-for-later) for the full round trip.
1370 hook_event_name: "Stop";1429 hook_event_name: "Stop";
1371 stop_hook_active: boolean;1430 stop_hook_active: boolean;
1372 last_assistant_message?: string;1431 last_assistant_message?: string;
1432 background_tasks?: BackgroundTaskSummary[];
1433 session_crons?: SessionCronSummary[];
1373};1434};
1374```1435```
1375 1436
1393 agent_transcript_path: string;1454 agent_transcript_path: string;
1394 agent_type: string;1455 agent_type: string;
1395 last_assistant_message?: string;1456 last_assistant_message?: string;
1457 background_tasks?: BackgroundTaskSummary[];
1458 session_crons?: SessionCronSummary[];
1459};
1460
1461type BackgroundTaskSummary = {
1462 id: string;
1463 type: string;
1464 status: string;
1465 description: string;
1466 command?: string;
1467 agent_type?: string;
1468 server?: string;
1469 tool?: string;
1470 name?: string;
1471};
1472
1473type SessionCronSummary = {
1474 id: string;
1475 schedule: string;
1476 recurring: boolean;
1477 prompt: string;
1396};1478};
1397```1479```
1398 1480
2708 2790
2709### `Usage`2791### `Usage`
2710 2792
2711Token usage statistics (from `@anthropic-ai/sdk`).2793Token usage statistics. This is the `BetaUsage` type from `@anthropic-ai/sdk`.
2712 2794
2713```typescript theme={null}2795```typescript theme={null}
2714type Usage = {2796type Usage = {
2715 input_tokens: number | null;2797 input_tokens: number;
2716 output_tokens: number | null;2798 output_tokens: number;
2717 cache_creation_input_tokens?: number | null;2799 cache_creation_input_tokens: number | null;
2718 cache_read_input_tokens?: number | null;2800 cache_read_input_tokens: number | null;
2801 cache_creation: {
2802 ephemeral_5m_input_tokens: number;
2803 ephemeral_1h_input_tokens: number;
2804 } | null;
2805 server_tool_use: BetaServerToolUsage | null;
2806 service_tier: "standard" | "priority" | "batch" | null;
2807 speed: "standard" | "fast" | null;
2808 inference_geo: string | null;
2809 iterations: BetaIterationsUsage | null;
2719};2810};
2720```2811```
2721 2812
2813`BetaServerToolUsage` and `BetaIterationsUsage` are defined in `@anthropic-ai/sdk`.
2814
2722### `CallToolResult`2815### `CallToolResult`
2723 2816
2724MCP tool result type (from `@modelcontextprotocol/sdk/types.js`). `structuredContent` is a JSON object that can be returned alongside `content`, including image blocks. See [Return structured data](/en/agent-sdk/custom-tools#return-structured-data).2817MCP tool result type (from `@modelcontextprotocol/sdk/types.js`). `structuredContent` is a JSON object that can be returned alongside `content`, including image blocks. See [Return structured data](/en/agent-sdk/custom-tools#return-structured-data).
2977 3070
2978### `SDKTaskProgressMessage`3071### `SDKTaskProgressMessage`
2979 3072
2980Emitted periodically while a background task is running.3073Emitted periodically while a subagent or background task is running. The `summary` field is populated only when [`agentProgressSummaries`](#options) is enabled.
2981 3074
2982```typescript theme={null}3075```typescript theme={null}
2983type SDKTaskProgressMessage = {3076type SDKTaskProgressMessage = {
2986 task_id: string;3079 task_id: string;
2987 tool_use_id?: string;3080 tool_use_id?: string;
2988 description: string;3081 description: string;
3082 subagent_type?: string;
2989 usage: {3083 usage: {
2990 total_tokens: number;3084 total_tokens: number;
2991 tool_uses: number;3085 tool_uses: number;
2992 duration_ms: number;3086 duration_ms: number;
2993 };3087 };
2994 last_tool_name?: string;3088 last_tool_name?: string;
3089 summary?: string;
2995 uuid: UUID;3090 uuid: UUID;
2996 session_id: string;3091 session_id: string;
2997};3092};