One change
Agent SDK reference - TypeScript
agent-sdk/typescript
agent-sdk/typescript Changed · +97 / -2 lines
### `SDKContextUsage` ### `SDKContextUsageCategory`
This page is larger than the 256 KiB this site keeps, so one side of the diff below stops where the stored text does.
from line 657
### `SDKControlGetContextUsageResponse` -Return type of [`getContextUsage()`](#query-object). This is the same payload the `/context` command renders in an interactive session, so alongside the token counts it carries display fields such as `color`, `gridRows`, and `percentage` that `/context` uses to draw its usage grid. +Return type of [`getContextUsage()`](#query-object). This is the same payload Claude Code renders for the `/context` command in an interactive session, so alongside the token counts it carries display fields such as `color` and `gridRows` that Claude Code uses to draw the `/context` usage grid. +When you send `/context` as a prompt instead of calling the method, Claude Code attaches an [`SDKContextUsage`](#sdkcontextusage) payload to the `context_usage` field of the assistant message that delivers the result. That field requires Agent SDK v0.3.232 or later. + ```typescript theme={null} type SDKControlGetContextUsageResponse = { categories: {
from line 762
* `memoryFiles` lists each loaded memory file with its cost. * `skills.skillFrontmatter` attributes the skill listing's tokens to each included skill. The per-skill counts measure each skill's listing entry as Claude Code actually sends it, which can be shorter than the skill's full frontmatter. Compare `skills.totalSkills` with `skills.includedSkills` to see whether every discovered skill made it into the listing. -`totalTokens` is the session's current context usage, and `maxTokens` is the window that usage is measured against. That window is the model's context window, or the lower auto-compaction window when one applies. Claude Code leaves the optional `deferredBuiltinTools`, `systemTools`, and `systemPromptSections` diagnostics unset, so expect them to be absent even though the type declares them. +`totalTokens` is the session's current context usage, and `maxTokens` is the window that usage is measured against. That window is the model's context window, or the lower auto-compaction window when one applies. `rawMaxTokens` carries the same value as `maxTokens`, and `percentage` is `totalTokens` as a rounded percentage of that window. +Claude Code leaves the optional `deferredBuiltinTools`, `systemTools`, and `systemPromptSections` diagnostics unset, so expect them to be absent even though the type declares them. + ### `SDKControlReadFileResponse` Return type of [`readFile()`](#query-object).
from line 1144
error?: SDKAssistantMessageError; aborted?: true; timestamp?: string; + context_usage?: SDKContextUsage; }; ```
from line 1156
`timestamp` is the ISO 8601 time when the message's content finished generating on the process that produced it. The value comes from that machine's clock, so use it for display only and don't order messages by it. One API turn can produce several assistant messages that share a `message.id`, each with its own `timestamp`. When the field is absent, fall back to the time you received the message. +`context_usage` is a structured copy of the `/context` report, typed as [`SDKContextUsage`](#sdkcontextusage), and requires Agent SDK v0.3.232 or later. When you send `/context` as a prompt, Claude Code delivers the report as an assistant message whose `message.content` holds the markdown table, and attaches `context_usage` to that same message. Claude Code doesn't set the field on any other assistant message, and earlier versions deliver the `/context` table without it, so read the breakdown from the field when it's present and fall back to the markdown text when it isn't. + ### `SDKUserMessage` User input message.
from line 1467
}; ``` +### `SDKContextUsage` + +Structured form of the `/context` report, carried as `context_usage` on the [`SDKAssistantMessage`](#sdkassistantmessage) that delivers a `/context` result. Agent SDK v0.3.232 and later export the type. Unlike [`SDKControlGetContextUsageResponse`](#sdkcontrolgetcontextusageresponse), it carries only the data needed to render the usage breakdown, without display fields such as `color` and `gridRows`. + +```typescript theme={null} +type SDKContextUsage = { + model: string; + total_tokens: number; + raw_max_tokens: number; + percentage: number; + over_limit?: { + tokens_over: number; + kind: "hard_limit" | "compaction_window"; + }; + categories: SDKContextUsageCategory[]; + mcp_tools: { + name: string; + server_name: string; + tokens: number; + }[]; + memory_files: { + path: string; + type: string; + tokens: number; + }[]; + agents: { + agent_type: string; + source: string; + tokens: number; + }[]; + skills?: { + name: string; + source: string; + plugin_name?: string; + tokens: number; + }[]; +}; +``` + +The table lists what Claude Code puts in each field. The fields from `model` through `over_limit` describe the session as a whole, and the collection fields attribute tokens to individual items. + +| Field | Type | Description | +| ---------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `model` | `string` | The main loop's model Claude Code computed the usage for, not a subagent's | +| `total_tokens` | `number` | Claude Code's estimate of the tokens in use. Not clamped to the window, so it can exceed `raw_max_tokens` when the session is over the limit | +| `raw_max_tokens` | `number` | The model's context window, or the lower [auto-compact window](/docs/en/model-config#context-window-and-auto-compaction) when one applies, such as one you set or the 200K boundary Claude Code applies to some models with a 1M-token window. Claude Code measures `total_tokens` against this window | +| `percentage` | `number` | `total_tokens` as a rounded percentage of `raw_max_tokens`, so it can exceed 100 when the session is over the limit | +| `over_limit` | `object` | Present only when `total_tokens` exceeds `raw_max_tokens`. `tokens_over` is the amount over, and `kind` says how Claude Code resolved the window | +| `categories` | [`SDKContextUsageCategory`](#sdkcontextusagecategory)`[]` | One entry per row of the usage-by-category breakdown | +| `mcp_tools` | `object[]` | Tokens attributed to each MCP tool, with its wire name, such as `mcp__linear__create_issue`, and its `server_name` | +| `memory_files` | `object[]` | Tokens attributed to each loaded memory file, with its `path` and a source label such as `Project` or `User` in `type` | +| `agents` | `object[]` | Tokens attributed to each custom subagent definition, with a source identifier such as `projectSettings`, `userSettings`, or `plugin`. Built-in subagents aren't listed | +| `skills` | `object[]` | Tokens attributed to each skill in the skill listing, with a source identifier and, for plugin skills, the plugin's name in `plugin_name`. Absent when no skills contribute tokens | + +`over_limit.kind` records how Claude Code resolved the window, not whether the API accepts the next request: + +* `hard_limit`: the window is what Claude Code believes to be the model's own limit, past which the API refuses requests +* `compaction_window`: the window is a compaction-policy window, which may or may not coincide with the model's limit + +Claude Code evolves the type additively, adding new data as optional fields rather than reshaping existing ones. Read the fields you know and ignore any you don't recognize. + +### `SDKContextUsageCategory` + +One row of the `/context` usage-by-category breakdown. + +```typescript theme={null} +type SDKContextUsageCategory = { + name: string; + tokens: number; + kind: "used" | "free" | "buffer" | "deferred"; +}; +``` + +The table lists what Claude Code puts in each field of a row. + +| Field | Type | Description | +| -------- | -------- | -------------------------------------------------------------------------------------------------------- | +| `name` | `string` | The row's display name as `/context` prints it, such as `Messages`. Classify rows by `kind`, not by name | +| `tokens` | `number` | The row's token count. Rows can carry zero tokens | +| `kind` | `string` | What the row represents: `used`, `free`, `buffer`, or `deferred` | + +Each `kind` value says what the row's tokens are: + +* `used`: content that occupies the context window +* `free`: the remaining window +* `buffer`: the compaction reserve +* `deferred`: tool schemas Claude Code holds out of the window and excludes from the usage calculation, listed for awareness + ### `SDKMessageOrigin` Provenance of a user-role message. This appears as `origin` on [`SDKUserMessage`](#sdkusermessage) and is forwarded onto the corresponding [`SDKResultMessage`](#sdkresultmessage) so you can tell what triggered a given turn.
from line 4321
| { type: "disabled" }; // No extended thinking ``` -The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `thinking` blocks. Claude Code doesn't send `display` to Amazon Bedrock or Google Cloud's Agent Platform, so on those providers Opus 4.7 and later return empty `thinking` blocks even when you set `display` to `"summarized"`. - -### `SpawnedProcess` - -Interface for custom process spawning (used with `spawnClaudeCodeProcess` option). `ChildProcess` already satisfies this interface. - -```typescript theme={null} -interface SpawnedProcess { - stdin: Writable; - stdout: Readable; - readonly killed: boolean; - readonly exitCode: number | null; - kill(signal: NodeJS.Signals): boolean; - on( - event: "exit", - listener: (code: number | null, signal: NodeJS.Signals | null) => void - ): void; - on(event: "error", listener: (error: Error) => void): void; - once( - event: "exit", - listener: (code: number | null, signal: NodeJS.Signals | null) => void - ): void; - once(event: "error", listener: (error: Error) => void): void; - off( - event: "exit", - listener: (code: number | null, signal: NodeJS.Signals | null) => void - ): void; - off(event: "error", listener: (error: Error) => void): void; -} -``` - -### `SpawnOptions` - -Options passed to the custom spawn function. - -```typescript theme={null} -interface SpawnOptions { - command: string; - args: string[]; - cwd?: string; - env: Record<string, string | undefined>; - signal: AbortSignal; -} -``` - -<Note> - The `signal` field tells your spawn function when to tear down the process. Pass it as the `signal` option to Node's `spawn()`, or pass it to your VM or container teardown handler. - - This signal does not fire the instant [`Options.abortController`](#options) aborts. The SDK first closes the process's stdin and waits about two seconds so the CLI can shut down cleanly, then aborts this signal. To react the moment the caller aborts instead, listen on your own `Options.abortController.signal`, which your spawn function can reference from its enclosing scope. -</Note> - -### `McpSetServersResult` - -Result of a `setMcpServers()` operation. - -```typescript theme={null} -type McpSetServersResult = { - added: string[]; - removed: string[]; - errors: Record<string, string>; -}; -``` - -### `RewindFilesResult` - -Result of a `rewindFiles()` operation. - -```typescript theme={null} -type RewindFilesResult = { - canRewind: boolean; - error?: string; - filesChanged?: string[]; - insertions?: number; - deletions?: number; - skippedLinks?: number; -}; -``` - -`skippedLinks` counts the tracked paths the rewind refused to restore or delete for link safety: a symlink, hard link, or other non-regular file at the tracked path, a parent directory that no longer resolves to where it pointed when the checkpoint was taken, or a backup that couldn't be read safely. The field requires Claude Code v2.1.216 or later. A preview call with `rewindFiles(userMessageId, { dryRun: true })` never sets it. - -### `SDKStatusMessage` - -Status update message (e.g., compacting). - -```typescript theme={null} -type SDKStatusMessage = { - type: "system"; - subtype: "status"; - status: "compacting" | null; - permissionMode?: PermissionMode; - uuid: UUID; - session_id: string; -}; -``` - -### `SDKTaskNotificationMessage` - -Notification when a background task completes, fails, or is stopped. Background tasks include `run_in_background` Bash commands, [Monitor](#monitor) watches, and background subagents. - -```typescript theme={null} -type SDKTaskNotificationMessage = { - type: "system"; - subtype: "task_notification"; - task_id: string; - tool_use_id?: string; - status: "completed" | "failed" | "stopped"; - output_file: string; - summary: string; - usage?: { - total_tokens: number; - tool_uses: number; - duration_ms: number; - }; - uuid: UUID; - session_id: string; -}; -``` - -Claude Code prepends a notice to every task notification it sends to the model, except deliveries stamped with the [`scheduled-trigger` subkind](#task-notification-subkinds), which carry an assigned-task framing instead. The notice states that no human input has occurred, so the model doesn't treat the notification as a user instruction or approval. - -To detect a task-notification turn, check `origin.kind === "task-notification"` on the [`SDKUserMessage`](#sdkusermessage) or [`SDKResultMessage`](#sdkresultmessage) rather than matching on the notice text. Read `subkind` from the same field if you need to know what raised it. Before v2.1.205, Claude Code left the notice off notifications that arrived while the session was idle. - -### `SDKToolUseSummaryMessage` - -Summary of tool usage in a conversation. - -```typescript theme={null} -type SDKToolUseSummaryMessage = { - type: "tool_use_summary"; - summary: string; - preceding_tool_use_ids: string[]; - uuid: UUID; - session_id: string; -}; -``` - -### `SDKHookStartedMessage` - -Emitted when a hook begins executing. - -Claude Code delivers this message, [`SDKHookProgressMessage`](#sdkhookprogressmessage), and [`SDKHookResponseMessage`](#sdkhookresponsemessage) to the message stream immediately, including while a `SessionStart` or `Setup` hook is still running during session startup. Claude Code v2.1.169 through v2.1.203 delivered these messages in one batch after a `SessionStart` or `Setup` hook completed; v2.1.204 restored live delivery. - -```typescript theme={null} -type SDKHookStartedMessage = { - type: "system"; - subtype: "hook_started"; - hook_id: string; - hook_name: string; - hook_event: string; - uuid: UUID; - session_id: string; -}; -``` - -### `SDKHookProgressMessage` - -Emitted while a hook is running, with stdout/stderr output. - -```typescript theme={null} -type SDKHookProgressMessage = { - type: "system"; - subtype: "hook_progress"; - hook_id: string; - hook_name: string; - hook_event: string; - stdout: string; - stderr: string; - output: string; - uuid: UUID; - session_id: string; -}; -``` - -### `SDKHookResponseMessage` - -Emitted when a hook finishes executing. - -```typescript theme={null} -type SDKHookResponseMessage = { - type: "system"; - subtype: "hook_response"; - hook_id: string; - hook_name: string; - hook_event: string; - output: string; - stdout: string; - stderr: string; - exit_code?: number; - outcome: "success" | "error" | "cancelled"; - uuid: UUID; - session_id: string; -}; -``` - -### `SDKToolProgressMessage` - -Emitted periodically while a tool is executing to indicate progress. - -```typescript theme={null} -type SDKToolProgressMessage = { - type: "tool_progress"; - tool_use_id: string; - tool_name: string; - parent_tool_use_id: string | null; - elapsed_time_seconds: number; - task_id?: string; - heartbeat?: boolean; - subagent_type?: string; - subagent_retry?: { - agent_id: string; - attempt: number; - max_retries: number; - retry_delay_ms: number; - error_status: number | null; - error_category: string; - }; - uuid: UUID; - session_id: string; -}; -``` - -While a tool call runs in the main conversation, Claude Code emits a `tool_progress` message every 30 seconds with `heartbeat: true`. Each heartbeat carries the tool name and elapsed seconds, so you can distinguish a long-running call from a stalled session. Claude Code doesn't emit heartbeats for the Agent tool, whose subagents stream their own progress, or for tool calls inside a subagent. The `heartbeat` field requires Agent SDK v0.3.214 or later. - -On `tool_progress` messages for the Agent tool, `subagent_type` names the running subagent type, such as `general-purpose`. `subagent_retry` is present while that subagent waits out an API error backoff, such as a rate limit or overload, with one message per retry attempt. Both fields require Agent SDK v0.3.214 or later. - -To render a retry indicator from `subagent_retry`: - -* Track the indicator by `parent_tool_use_id`, which is unique per subagent. `tool_use_id` is shared by parallel subagents from one assistant turn, so tracking by it would let one subagent's update clear another's indicator. -* Clear the indicator when a later `tool_progress` for the same `parent_tool_use_id` arrives without the field, or when the tool's result message arrives. `attempt` can exceed `max_retries` under persistent retry, so don't derive clearing from the counters. -* Treat `error_category` as a closed set of tokens for choosing your own message text, not as display text: `rate_limit`, `overloaded`, `authentication_failed`, `server_error`, or `unknown`. - -### `SDKAuthStatusMessage` - -Emitted during authentication flows. - -```typescript theme={null} -type SDKAuthStatusMessage = { - type: "auth_status"; - isAuthenticating: boolean; - output: string[]; - error?: string; - uuid: UUID; - session_id: string; -}; -``` - -### `SDKTaskStartedMessage` - -Emitted when a background task begins. The ` +The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `thinking` blocks. Claude Code doesn't send `display` to A