Changes on
47 changes detected
--- a/agent-loop.md
+++ b/agent-loop.md
@@ -95,6 +95,28 @@
print(f"Session ended with an error: {error}")
asyncio.run(main())
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ try {
+ for await (const message of query({ prompt: "Summarize this project" })) {
+ if (message.type === "assistant") {
+ console.log(`Turn completed: ${message.message.content.length} content blocks`);
+ }
+ if (message.type === "result") {
+ if (message.subtype === "success") {
+ console.log(message.result);
+ } else {
+ console.log(`Stopped: ${message.subtype}`);
+ }
+ }
+ }
+ } catch (error) {
+ // A single-shot query() throws after yielding an error result. If the
+ // failure was an error result, the error subtype branches above have
+ // already run; connection or process failures yield no result message.
+ console.log(`Session ended with an error: ${error}`);
+ }
##
@@ -399,6 +421,47 @@
asyncio.run(run_agent())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ let sessionId: string | undefined;
+
+ try {
+ for await (const message of query({
+ prompt: "Find and fix the bug causing test failures in the auth module",
+ options: {
+ allowedTools: ["Read", "Edit", "Bash", "Glob", "Grep"], // Listing tools here auto-approves them (no prompting)
+ settingSources: ["project"], // Load CLAUDE.md, skills, hooks from current directory
+ maxTurns: 30, // Prevent runaway sessions
+ effort: "high" // Thorough reasoning for complex debugging
+ }
+ })) {
+ // Save the session ID to resume later if needed
+ if (message.type === "system" && message.subtype === "init") {
+ sessionId = message.session_id;
+ }
+
+ // Handle the final result
+ if (message.type === "result") {
+ if (message.subtype === "success") {
+ console.log(`Done: ${message.result}`);
+ } else if (message.subtype === "error_max_turns") {
+ // Agent ran out of turns. Resume with a higher limit.
+ console.log(`Hit turn limit. Resume session ${sessionId} to continue.`);
+ } else if (message.subtype === "error_max_budget_usd") {
+ console.log("Hit budget limit.");
+ } else {
+ console.log(`Stopped: ${message.subtype}`);
+ }
+ console.log(`Cost: $${message.total_cost_usd.toFixed(4)}`);
+ }
+ }
+ } catch (error) {
+ // A single-shot query() throws after yielding an error result. If the
+ // failure was an error result, the error subtype branches above have
+ // already run; connection or process failures yield no result message.
+ console.log(`Session ended with an error: ${error}`);
+ }
+
##
--- a/agent-view.md
+++ b/agent-view.md
@@ -150,7 +150,7 @@
Attach to a session
-Press `Enter` or `→` on a selected row to attach. Agent view is replaced by the full interactive session. When you attach, Claude posts a short recap of what happened while you were away. While attached, the session behaves like any other Claude Code session: every [command](</docs/en/commands>), keyboard shortcut, and feature works. Attached sessions always render in [fullscreen mode](</docs/en/fullscreen>), regardless of your `tui` setting, because a background session has no terminal scrollback to append to. Scroll with `PgUp`, `PgDn`, or the mouse wheel, and press `Ctrl+O` for transcript mode. Your terminal’s native scroll and tmux copy mode show only the current viewport, the same as when you run any fullscreen application. Press `←` on an empty prompt, or run `/exit`, to detach and return to agent view. As of v2.1.198 this works the same way whether you opened the session from agent view or with `claude attach <id>` from your shell. `Ctrl+Z` also detaches but goes back to where you started instead: agent view if you attached from there, or your shell if you ran `claude attach`. Use `Ctrl+Z` when a dialog has focus and isn’t responding to `←`. `Ctrl+C` keeps its standard interrupt behavior while attached: it cancels a running response or `!` shell command rather than detaching. Pressing `Ctrl+C` twice on an empty prompt detaches, the same as in any session. Detaching never stops a background session: `←`, `Ctrl+Z`, `/exit`, and double `Ctrl+C` or double `Ctrl+D` all leave it running. To end a session from inside it, run `/stop`. In a session running in the foreground, one you started in the terminal rather than attached to from agent view, pressing `←` on an empty prompt backgrounds it and opens agent view with that row selected, so you can switch sessions without leaving the terminal. The same single press detaches an attached session. If a tool is running when you press `←`, Claude Code waits up to about ten seconds for it to finish before backgrounding, and the response continues in the background session. Press `←` again to background immediately instead of waiting. When in-flight work can’t carry over to the background session, the `Background this session?` dialog appears first, the same as with `/background`. The row is created even from a fresh session with no conversation history, so `→` returns to it. When that row is the only one, agent view shows an onboarding hint below it. You can turn this shortcut off with the `leftArrowOpensAgents` setting in `/config`.
+Press `Enter` or `→` on a selected row to attach. Agent view is replaced by the full interactive session. When you attach, Claude posts a short recap of what happened while you were away. While attached, the session behaves like any other Claude Code session: every [command](</docs/en/commands>), keyboard shortcut, and feature works. Attached sessions always render in [fullscreen mode](</docs/en/fullscreen>), regardless of your `tui` setting, because a background session has no terminal scrollback to append to. Scroll with `PgUp`, `PgDn`, or the mouse wheel, and press `Ctrl+O` for transcript mode. Your terminal’s native scroll and tmux copy mode show only the current viewport, the same as when you run any fullscreen application. Press `←` on an empty prompt, or run `/exit`, to detach and return to agent view. As of v2.1.198 this works the same way whether you opened the session from agent view or with `claude attach <id>` from your shell. `Ctrl+Z` also detaches but goes back to where you started instead: agent view if you attached from there, or your shell if you ran `claude attach`. Use `Ctrl+Z` when a dialog has focus and isn’t responding to `←`. `Ctrl+C` keeps its standard interrupt behavior while attached: it cancels a running response or `!` shell command rather than detaching. Pressing `Ctrl+C` twice on an empty prompt detaches, the same as in any session. Detaching never stops a background session: `←`, `Ctrl+Z`, `/exit`, and double `Ctrl+C` or double `Ctrl+D` all leave it running. To end a session from inside it, run `/stop`. In a session running in the foreground, one you started in the terminal rather than attached to from agent view, pressing `←` on an empty prompt backgrounds it and opens agent view with that row selected, so you can switch sessions without leaving the terminal. The same single press detaches an attached session. If a tool is running when you press `←`, Claude Code waits up to about ten seconds for it to finish before backgrounding, and the response continues in the background session. Press `←` again to background immediately instead of waiting. When in-flight work can’t carry over to the background session, the `Background this session?` dialog appears first, the same as with `/background`. The ten-second limit doesn’t apply while [subagents](</docs/en/sub-agents>) are running. Claude Code keeps waiting so their work carries over, and shows a `Still backgrounding after the current tool` notice while it waits; press `←` again to background without waiting, which restarts the subagents from the beginning. Before v2.1.203, the wait ended after ten seconds and the running subagents were restarted from the beginning without warning. The row is created even from a fresh session with no conversation history, so `→` returns to it. Before v2.1.203, agent view showed an onboarding hint below that row when it was the only one. You can turn this shortcut off with the `leftArrowOpensAgents` setting in `/config`.
###
@@ -242,7 +242,7 @@
* `/model` sets the dispatch model
* As of v2.1.198, `/login` opens the sign-in dialog so you can sign in again without attaching to a session
-Skills, your own commands, and prompt-expanding built-ins such as `/init` are sent to a new background session as their first prompt. Other built-in commands show an `attach to a session to run it` hint instead. Packaging a recurring task as a [skill](</docs/en/skills>) lets you start the same workflow from agent view repeatedly without retyping the prompt. When the same `@name` matches both a subagent and a sibling repository, the subagent takes precedence. The bare first-word match also applies, so a prompt that happens to begin with one of your subagent names dispatches that subagent rather than treating the word as plain text. Use the `@` form when you want to be explicit, or start the prompt with a different word to avoid the match.
+Skills, your own commands, and prompt-expanding built-ins such as `/init` are sent to a new background session as their first prompt. Other built-in commands show an `attach to a session to run it` hint instead. Everything you typed stays in the input next to the hint so you can edit it. Before v2.1.203, the hint cleared the input and the typed text was lost. Packaging a recurring task as a [skill](</docs/en/skills>) lets you start the same workflow from agent view repeatedly without retyping the prompt. When the same `@name` matches both a subagent and a sibling repository, the subagent takes precedence. The bare first-word match also applies, so a prompt that happens to begin with one of your subagent names dispatches that subagent rather than treating the word as plain text. Use the `@` form when you want to be explicit, or start the prompt with a different word to avoid the match.
####
@@ -253,7 +253,11 @@
A new session runs in the directory you opened agent view from. To target a different directory, use any of these:
* Open `claude agents` in that directory.
- * Open `claude agents` in a parent directory and mention a child repository with `@<repo>` in the prompt. Typing `@` lists git repositories one level below the launch directory, plus any directory that already has a session in the list. A directory whose name contains a space isn’t listed.
+ * Open `claude agents` in a parent directory and mention a child repository with `@<repo>` in the prompt. Typing `@` lists these targets:
+ * Git repositories one level below the launch directory
+ * The registered [git worktrees](</docs/en/worktrees>) of the repository you launched from that live inside its directory tree, such as the ones Claude creates under `.claude/worktrees/`, labeled with their checked-out branch. Worktrees added outside the repository, such as with `git worktree add ../feature`, aren’t listed
+ * Any directory that already has a session in the list
+A directory whose name contains a space isn’t listed. Before v2.1.203, registered worktrees weren’t listed, so dispatching into one meant running `claude --bg` from that worktree’s directory.
* From the shell, `cd` into the directory and run `claude --bg "<prompt>"`.
When agent view is grouped by directory, the highlighted row’s directory becomes the dispatch target, so you can scroll to a group and dispatch into it without retyping the path.
@@ -337,7 +341,7 @@
}
}
-Outside a git repository, sessions write to the working directory directly and aren’t isolated from each other, so avoid dispatching parallel sessions that edit the same files. If you use a different version control system, configure a [`WorktreeCreate` hook](</docs/en/worktrees#non-git-version-control>) and Claude isolates edits the same way it does for git. Deleting a session in agent view with `Ctrl+X` twice removes a worktree Claude created for it, including any uncommitted changes, so merge or push the changes you want to keep first. Deleting from the shell with `claude rm` keeps a worktree that has uncommitted changes and prints its path so you can clean it up yourself. A worktree you created yourself and started the session inside is left in place either way. To find a session’s worktree path, peek the session or attach and check its working directory. A [subagent](</docs/en/sub-agents>) the background session spawns inherits the session’s working directory, so its file edits land in the session’s worktree rather than your working copy. To give a subagent its own separate worktree instead, set [`isolation: worktree`](</docs/en/sub-agents#supported-frontmatter-fields>) in its frontmatter or pass `isolation: "worktree"` when spawning it. As of v2.1.198, a background session that isolated its code changes in a worktree also commits, pushes its own branch, and opens a draft pull request without stopping to ask. The `#N` label appears on its row when the pull request opens. It never pushes to `main` or `master`, never force-pushes or merges, and it skips the pull request when you told it not to open one or the repository has no remote. A session editing a checkout it didn’t isolate itself still asks before committing or switching branches. This applies when isolation is set to `"none"`, when the worktree move failed, or when the session started inside a worktree that already existed.
+Outside a git repository, sessions write to the working directory directly and aren’t isolated from each other, so avoid dispatching parallel sessions that edit the same files. If you use a different version control system, configure a [`WorktreeCreate` hook](</docs/en/worktrees#non-git-version-control>) and Claude isolates edits the same way it does for git. When the hook fails in a directory that isn’t a git repository, the session skips isolation for that directory and edits the working directory in place. Inside a git repository, writes stay blocked until the session isolates. Before v2.1.203, a background session in that state couldn’t edit any file: every write was rejected until it isolated, and the hook could never isolate that directory. Deleting a session in agent view with `Ctrl+X` twice removes a worktree Claude created for it, including any uncommitted changes, so merge or push the changes you want to keep first. Deleting from the shell with `claude rm` keeps a worktree that has uncommitted changes and prints its path so you can clean it up yourself. A worktree you created yourself and started the session inside is left in place either way. To find a session’s worktree path, peek the session or attach and check its working directory. A [subagent](</docs/en/sub-agents>) the background session spawns inherits the session’s working directory, so its file edits land in the session’s worktree rather than your working copy. To give a subagent its own separate worktree instead, set [`isolation: worktree`](</docs/en/sub-agents#supported-frontmatter-fields>) in its frontmatter or pass `isolation: "worktree"` when spawning it. As of v2.1.198, a background session that isolated its code changes in a worktree also commits, pushes its own branch, and opens a draft pull request without stopping to ask. The `#N` label appears on its row when the pull request opens. It never pushes to `main` or `master`, never force-pushes or merges, and it skips the pull request when you told it not to open one or the repository has no remote. A session editing a checkout it didn’t isolate itself still asks before committing or switching branches. This applies when isolation is set to `"none"`, when the worktree move failed, or when the session started inside a worktree that already existed.
###
@@ -364,7 +368,7 @@
Permission mode, model, and effort
-A background session reads its [settings](</docs/en/settings>) from the directory it runs in, the same as if you had started `claude` there. This includes [`env` values](</docs/en/settings#available-settings>) in project settings, so an `ANTHROPIC_MODEL` or provider variable set there applies to background sessions in that directory. Cloud provider selection, such as `CLAUDE_CODE_USE_BEDROCK` or `CLAUDE_CODE_USE_VERTEX`, and `ANTHROPIC_DEFAULT_*_MODEL` aliases follow the shell that dispatched the session. Gateway endpoint variables such as `ANTHROPIC_BASE_URL` and its paired `ANTHROPIC_AUTH_TOKEN` don’t. See the supervisor process for how background sessions source provider settings and credentials. The [permission mode](</docs/en/permissions>) depends on how you started the session. Backgrounding an existing session with `/bg` or `←` keeps the current permission mode, so a session you switched to `acceptEdits` or `auto` stays in that mode after detaching. Dispatching from the agent view input or running `claude --bg` from your shell uses the `defaultMode` from that directory’s settings, or the `permissionMode` from the dispatched [subagent’s frontmatter](</docs/en/sub-agents#supported-frontmatter-fields>). The permission mode, model, and effort a background session was started with, along with the configuration flags it carries, all persist when the supervisor later stops and restarts its process. A session you launched with `claude --bg --dangerously-skip-permissions` or `claude --bg --permission-mode bypassPermissions` stays in `bypassPermissions` after that restart instead of falling back to the directory’s `defaultMode`, and a model or effort you changed mid-session with `/model` or `/effort` is kept. A name you set with [`/rename`](</docs/en/commands>) or `Ctrl+R` also persists across that restart, so [`claude --resume <name>`](</docs/en/sessions#name-your-sessions>) still resolves the session. Before v2.1.202, the restart reverted the session to the name it was dispatched with and the new name stopped resolving. To set defaults for every session you dispatch from agent view, pass any of `--permission-mode`, `--model`, `--effort`, or `--agent` when opening it:
+A background session reads its [settings](</docs/en/settings>) from the directory it runs in, the same as if you had started `claude` there. This includes [`env` values](</docs/en/settings#available-settings>) in project settings, so an `ANTHROPIC_MODEL` or provider variable set there applies to background sessions in that directory. Cloud provider selection, such as `CLAUDE_CODE_USE_BEDROCK` or `CLAUDE_CODE_USE_VERTEX`, and `ANTHROPIC_DEFAULT_*_MODEL` aliases follow the shell that dispatched the session. A gateway `ANTHROPIC_BASE_URL` exported in that shell follows it too, together with `ANTHROPIC_CUSTOM_HEADERS`, when the supervisor runs with the same gateway environment and the session runs in the directory you dispatch from or is your own session backgrounded with `←` or `/background`. That is the normal case when the first shell to open agent view or dispatch a background session is the gateway shell. Dispatching into a different directory with `@repo` or `--cwd` doesn’t carry the shell’s gateway; that project’s [settings](</docs/en/settings>) supply the endpoint. See the supervisor process for how background sessions source provider settings and credentials. The [permission mode](</docs/en/permissions>) depends on how you started the session. Backgrounding an existing session with `/bg` or `←` keeps the current permission mode, so a session you switched to `acceptEdits` or `auto` stays in that mode after detaching. Dispatching from the agent view input or running `claude --bg` from your shell uses the `defaultMode` from that directory’s settings, or the `permissionMode` from the dispatched [subagent’s frontmatter](</docs/en/sub-agents#supported-frontmatter-fields>). The permission mode, model, and effort you chose for a background session, along with the configuration flags it carries, all persist when the supervisor later stops and restarts its process. A session you launched with `claude --bg --dangerously-skip-permissions` or `claude --bg --permission-mode bypassPermissions` stays in `bypassPermissions` after that restart instead of falling back to the directory’s `defaultMode`, and a model or effort you changed mid-session with `/model` or `/effort` is kept. An effort the session took from the [`effortLevel` setting](</docs/en/settings#available-settings>) rather than from `--effort` or `/effort` isn’t fixed at dispatch: each process started for the session reads the setting again, so editing `effortLevel` in `settings.json` reaches sessions you background with `←` or `/bg` and their later restarts. Before v2.1.203, backgrounding a session recorded its settings-derived effort as if you had passed `--effort`, so later `effortLevel` edits never reached it. A name you set with [`/rename`](</docs/en/commands>) or `Ctrl+R` also persists across that restart, so [`claude --resume <name>`](</docs/en/sessions#name-your-sessions>) still resolves the session. Before v2.1.202, the restart reverted the session to the name it was dispatched with and the new name stopped resolving. To set defaults for every session you dispatch from agent view, pass any of `--permission-mode`, `--model`, `--effort`, or `--agent` when opening it:
claude agents --permission-mode plan --model opus --effort high
@@ -426,7 +430,7 @@
The supervisor process
-Background sessions are hosted by a per-user supervisor process, separate from your terminal and from agent view. The supervisor starts automatically the first time you background a session or open agent view, and you don’t manage it directly. The supervisor keeps one pre-warmed worker process ready so a dispatch from agent view or `claude --bg` starts without the delay of a cold launch. When you dispatch, the supervisor assigns the pre-warmed worker to your session, applies that session’s directory, settings, and credentials to it, and then starts a replacement for the next dispatch. If no healthy pre-warmed worker is available, the supervisor launches a fresh process instead. The supervisor and its sessions authenticate with the same stored credentials as your interactive sessions and make no additional network connections beyond the model API. Provider selection variables such as `CLAUDE_CODE_USE_BEDROCK` and `ANTHROPIC_DEFAULT_*_MODEL` aliases are read from the shell that dispatched each session and are applied to its worker. A background session doesn’t inherit gateway endpoint variables such as `ANTHROPIC_BASE_URL`, the equivalent Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry base URL variables, or a paired `ANTHROPIC_AUTH_TOKEN` from the shell that started the supervisor or from the dispatching shell. The session uses your stored credentials and any `env` values in the project directory’s [settings](</docs/en/settings>) instead. To point background sessions in a project at an [LLM gateway](</docs/en/llm-gateway>), set `ANTHROPIC_BASE_URL` in that project’s `.claude/settings.json` `env` block rather than exporting it in your shell. Each background session is its own Claude Code process, managed by the supervisor rather than tied to your terminal. A session that’s actively working, waiting for your input, or has a terminal attached keeps its process running. A running background shell command, subagent, dynamic workflow, or monitor counts as active work, so a long-running process such as a dev server keeps the session alive. Once a session finishes and sits unattached for about an hour, the supervisor stops its process to free resources. A session you have pinned with `Ctrl+T` is exempt and keeps its process running while idle. The transcript and state stay on disk either way, and the next time you attach, peek, or reply to a stopped session, the supervisor starts a fresh process from where it left off. When every session has finished and no terminal is connected, the supervisor itself exits and starts again the next time you need it. Background work the session itself started at the top level is handed off when its process is stopped, restarted, or updated, including on Windows. The next process started for that session picks the work back up:
+Background sessions are hosted by a per-user supervisor process, separate from your terminal and from agent view. The supervisor starts automatically the first time you background a session or open agent view, and you don’t manage it directly. The supervisor keeps one pre-warmed worker process ready so a dispatch from agent view or `claude --bg` starts without the delay of a cold launch. When you dispatch, the supervisor assigns the pre-warmed worker to your session, applies that session’s directory, settings, and credentials to it, and then starts a replacement for the next dispatch. If no healthy pre-warmed worker is available, the supervisor launches a fresh process instead. The supervisor and its sessions authenticate with the same stored credentials as your interactive sessions and make no additional network connections beyond the model API. Provider selection variables such as `CLAUDE_CODE_USE_BEDROCK` and `ANTHROPIC_DEFAULT_*_MODEL` aliases are read from the shell that dispatched each session and are applied to its worker. The dispatching shell’s `PATH` is applied to the worker the same way, so shell commands the session runs find the same tools your terminal does. Before v2.1.203, a background session kept the `PATH` of the shell that first started the supervisor, so tools added to your `PATH` since then could be missing, most often on Windows. A background session doesn’t inherit gateway endpoint variables such as `ANTHROPIC_BASE_URL` or the equivalent Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry base URL variables from the shell that started the supervisor. Without a gateway exported in the shell you dispatch from, the session uses your stored credentials and any `env` values in the project directory’s [settings](</docs/en/settings>). To point every session in a project at an [LLM gateway](</docs/en/llm-gateway>), set `ANTHROPIC_BASE_URL` in that project’s `.claude/settings.json` `env` block. A gateway `ANTHROPIC_BASE_URL` exported in the shell you dispatch from reaches that session’s worker, together with `ANTHROPIC_CUSTOM_HEADERS` and the credential exported alongside them, when the supervisor was started from an environment with the same gateway. The supervisor captures its environment from the first shell that opens agent view or dispatches a background session, so starting from the gateway shell gives it that environment. The forward also applies only to sessions dispatched into the directory you’re dispatching from, or backgrounded from your own session with `←` or `/background`: dispatching into a different directory with `@repo` or `--cwd` doesn’t carry the shell’s gateway, and that project’s `settings.json` `env` block supplies the endpoint instead. When the supervisor’s environment carries a different gateway or none, the worker keeps your stored credentials against the default endpoint instead of mixing one environment’s credential with another’s endpoint. Before v2.1.203, the dispatching shell’s `ANTHROPIC_BASE_URL` was dropped while the `ANTHROPIC_API_KEY` exported alongside it was kept, so the gateway’s key was sent to the default endpoint and every request failed with a 401. The forwarded endpoint applies only to that live process and is never written to disk. When the supervisor stops an idle session and later restarts it, the restarted process reads its endpoint from your settings again: with a gateway `ANTHROPIC_AUTH_TOKEN` it falls back to your stored credentials, and with a gateway-issued `ANTHROPIC_API_KEY` it can fail to authenticate until the gateway is set in settings. Each background session is its own Claude Code process, managed by the supervisor rather than tied to your terminal. A session that’s actively working, waiting for your input, or has a terminal attached keeps its process running. A running background shell command, subagent, dynamic workflow, or monitor counts as active work, so a long-running process such as a dev server keeps the session alive. Once a session finishes and sits unattached for about an hour, the supervisor stops its process to free resources. A session you have pinned with `Ctrl+T` is exempt and keeps its process running while idle. The transcript and state stay on disk either way, and the next time you attach, peek, or reply to a stopped session, the supervisor starts a fresh process from where it left off. When every session has finished and no terminal is connected, the supervisor itself exits and starts again the next time you need it. Background work the session itself started at the top level is handed off when its process is stopped, restarted, or updated, including on Windows. The next process started for that session picks the work back up:
* A background shell command that finished in the meantime is reported as completed with its output
* A dynamic workflow resumes from where it left off
@@ -479,7 +483,7 @@
Agent view opens with no sessions
-Before you dispatch your first session, agent view shows a short onboarding hint with example prompts in place of the session list. Type a prompt in the input at the bottom and press `Enter` to dispatch your first session.
+Before you dispatch your first session, agent view shows the empty section headers with a description under each, plus a one-line explanation above the input, in place of the session list. Type a prompt in the input at the bottom and press `Enter` to dispatch your first session.
###
@@ -504,6 +508,14 @@
Sessions show as failed after shutdown
Shutting down or restarting your machine stops running background sessions, so they show as failed when you next open agent view. Attach, peek, or reply to any of them and the session restarts from where it left off. Sleep alone doesn’t cause this. Sessions are preserved across sleep and the supervisor reconnects to them on wake.
+
+###
+
+
+
+Opening a session says the conversation is already open
+
+Opening a stopped row whose conversation is also held open by another running non-interactive Claude Code process, for example a background worker for the same conversation that is still winding down, shows `This conversation is already open in another running Claude session` instead of starting the row’s process, because two processes can’t write to the same transcript. Reply in the session that already has the conversation open, or exit it and open the row again. A reply you typed with the refused attempt isn’t lost; it’s sent the next time the session starts. Before v2.1.203, this state started a second process anyway. That process exited with a `currently running as a background agent` error and the row showed as failed.
###
@@ -603,6 +615,7 @@
Version| Change
---|---
+v2.1.203| A gateway `ANTHROPIC_BASE_URL` exported in the dispatching shell reaches the sessions dispatched from it into that same directory when the supervisor shares that gateway environment, instead of being dropped while the API key exported alongside it was kept. The dispatching shell’s `PATH` is applied to each session’s worker. Pressing `←` while subagents are running waits for them instead of restarting them after ten seconds. The empty list always shows the section headers with a description under each. Typing `@` in the dispatch input also lists the launch repository’s registered git worktrees that live inside its directory tree. An effort inherited from the `effortLevel` setting follows later edits to that setting instead of being fixed at dispatch. Opening a stopped session whose conversation is already open in another running session is refused with a message instead of failing the row. A command that isn’t available in agent view leaves the typed text in the input. A `WorktreeCreate` hook that fails outside a git repository no longer blocks the session from editing files.
v2.1.202| A name set with `/rename` or `Ctrl+R` on a background session persists when the supervisor stops and restarts its process, instead of reverting to the name the session was dispatched with.
v2.1.200| An older Claude Code version that rewrites the session list in `roster.json` preserves fields written by a newer version, matching the existing `state.json` guarantee, so sessions started by the newer version keep accepting input after the supervisor restarts. When you open a session that has stopped responding, the supervisor restarts its process and the session continues the interrupted response from where it left off.
v2.1.199| A background session whose process exits before it finishes starting on a low-memory host shows `possibly low memory — free some up and retry` in its row status instead of only the bare exit reason. Backgrounding a session with `←` or `/background` carries its `/color` over to the new row.
--- a/authentication.md
+++ b/authentication.md
@@ -154,6 +154,14 @@
+Renew an expiring login
+
+When the login you created with `/login` is within five days of expiring, Claude Code shows a warning at startup: `Your login expires in 3 days · run /login to renew`. Requires Claude Code v2.1.203 or later. Run `/login` to renew. The warning is informational and never blocks a request: authentication keeps working until the login actually expires. The login lifetime itself is unchanged; the advance warning is what v2.1.203 adds. The warning appears only when a claude.ai or Claude Console login is the active credential, and not when a cloud provider, `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` supplies the credential. Renewing early matters most for sessions that run unattended. A [background session in agent view](</docs/en/agent-view>) or a [Remote Control](</docs/en/remote-control>) session that outlives the login stops making progress once the credential expires and can’t recover until you sign in again.
+
+###
+
+
+
Authentication precedence
When multiple credentials are present, Claude Code chooses one in this order:
--- a/auto-mode-config.md
+++ b/auto-mode-config.md
@@ -51,7 +51,7 @@
* **Network posture**
* **Protected deployment namespaces / environments** : falls back to the Sensitive remote targets heuristic until you name them
* **Data retention / declassification**
- * **Trust slots** : name what the classifier treats as inside your boundary. The slots are Trusted repo, Source control, Trusted internal domains, Trusted cloud buckets, Key internal services, and Internal package registry. The repo and source-control entries default to the working repository and its configured remotes. Every other trust slot defaults to `None configured`, so nothing else is trusted until you add it.
+ * **Trust slots** : name what the classifier treats as inside your boundary. The slots are Trusted repo, Source control, Trusted internal domains, Trusted cloud buckets, Key internal services, and Internal package registry. The repo and source-control entries default to the working repository and its configured remotes. Every other trust slot defaults to `None configured`, so nothing else is trusted until you add it. A repository’s visibility scopes only confidential material: a private repository is an acceptable destination for confidential material, but making a repository private never clears secrets or personal or entrusted data into it, and the classifier treats content ported, repointed, or first read from outside the working repository as not that repository’s own work. This scoping requires Claude Code v2.1.203 or later.
* **Sensitivity slots** : name what the protective rules treat as high-risk. The slots are Sensitive data locations & audiences, Sensitive remote targets, and Protected IaC scopes. Each defaults to a broad heuristic, such as treating any host or namespace whose name carries `prod` or `production` as a sensitive remote target, so the protective rules are active before you configure anything. Naming concrete targets in a sensitivity slot makes those rules apply to the named targets instead of the heuristic.
To add your own entries alongside the defaults, include the literal string `"$defaults"` in the array. The default entries are spliced in at that position, so your custom entries can go before or after them. The following example keeps the default entries and adds an organization’s repos, buckets, domains, and services.
--- a/changelog.md
+++ b/changelog.md
@@ -1,4 +1,34 @@
This page is generated from the [CHANGELOG.md on GitHub](<https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md>). Run `claude --version` to check your installed version.
+
+
+
+2.1.205
+
+July 8, 2026
+
+ * Added an auto mode rule that blocks tampering with session transcript files
+ * Fixed `--json-schema` silently producing unstructured output when the schema was invalid, and schemas using the `format` keyword being rejected
+ * Fixed a message sent while Claude was working being silently lost when the turn ended at the `--max-turns` limit
+ * Fixed Windows worktree removal deleting files outside the worktree when an NTFS junction or directory symlink existed inside it
+ * Fixed background agents staying shown as “failed” or “completed” in the agent list after being resumed with `SendMessage`
+ * Fixed background jobs flipping from “needs input” back to “working” in the agent list when the agent’s turn contained no readable text
+ * Fixed `claude attach` erroring when a background agent was mid-upgrade restart instead of waiting for it to come back
+ * Fixed session-to-PR linking missing a PR created in a Bash call whose output exceeded the 30K inline limit
+ * Fixed `claude mcp add-from-claude-desktop` getting stuck when a server name contains unsupported characters; invalid names are now reported and remaining servers still import
+ * Fixed a plugin LSP server that fails to initialize preventing a valid LSP server from another plugin handling the same file extension
+ * Fixed a Windows crash when the directory Claude was launched from is deleted, locked, or unmounted while a command is running
+ * Fixed a crash when a file watcher was closed while a directory scan was still in flight
+ * Fixed project verify skills being rewritten on every session instead of only when a documented command changed
+ * Fixed the agent view rendering one line too high and clipping its header when the job list slightly overflowed the screen
+ * Fixed background tasks in the web and mobile Remote Control panels showing stale “Running” status by forwarding full task state on every membership change
+ * Improved auto mode to ask before running `rm -rf` on a variable it can’t resolve from context
+ * Auto-update binary downloads now stream to disk instead of buffering in memory, cutting the updater’s peak memory usage by roughly 400 MB
+ * Background task notifications now explicitly state that no human input has occurred, preventing fabricated in-transcript approvals from being acted on
+ * Improved agent view: sessions that edit, merge, comment on, or push to an existing PR now link it in `claude agents`
+ * Improved agent view: rows now show a colored state word and a classifier-written headline instead of raw tool call text, and the peek opens with full status including the exact ask for blocked sessions
+ * `/doctor` is now a full setup checkup that can diagnose and fix issues; `/checkup` is its alias
+ * Reserved the “Claude Browser” MCP server name (alongside “Claude Preview”) ahead of the Claude Desktop pane rename; user-configured MCP servers can no longer register under either name
+ * Fixed Cowork VM-mode local-agent sessions failing to start with “Not logged in · Please run /login” on CLI 2.1.203+
--- a/claude-code-features.md
+++ b/claude-code-features.md
@@ -31,6 +31,28 @@
if isinstance(message, ResultMessage) and message.subtype == "success":
print(f"\nResult: {message.result}")
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Help me refactor the auth module",
+ options: {
+ // "user" loads from ~/.claude/, "project" loads from ./.claude/ in cwd.
+ // Together they give the agent access to CLAUDE.md, skills, hooks, and
+ // permissions from both locations.
+ settingSources: ["user", "project"],
+ allowedTools: ["Read", "Edit", "Bash"]
+ }
+ })) {
+ if (message.type === "assistant") {
+ for (const block of message.message.content) {
+ if (block.type === "text") console.log(block.text);
+ }
+ }
+ if (message.type === "result" && message.subtype === "success") {
+ console.log(`\nResult: ${message.result}`);
+ }
+ }
+
Each source loads settings from a specific location, where `<cwd>` is the working directory you pass via the `cwd` option, or the process’s current directory if unset. For the full type definition, see [`SettingSource`](</docs/en/agent-sdk/typescript#settingsource>) (TypeScript) or [`SettingSource`](</docs/en/agent-sdk/python#settingsource>) (Python).
Source| What it loads| Location
@@ -114,6 +136,23 @@
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Skills in .claude/skills/ are discovered automatically
+ // when settingSources includes "project"
+ for await (const message of query({
+ prompt: "Review this PR using our code review checklist",
+ options: {
+ settingSources: ["user", "project"],
+ skills: "all",
+ allowedTools: ["Read", "Grep", "Glob"]
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success") {
+ console.log(message.result);
+ }
+ }
Skills must be created as filesystem artifacts (`.claude/skills/<name>/SKILL.md`). The SDK does not have a programmatic API for registering skills. See [Agent Skills in the SDK](</docs/en/agent-sdk/skills>) for full details.
@@ -170,6 +209,42 @@
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
+ import { query, type HookInput, type HookJSONOutput } from "@anthropic-ai/claude-agent-sdk";
+
+ // PreToolUse hook callback. HookInput is a discriminated union on
+ // hook_event_name, so narrowing on it gives TypeScript the right
+ // tool_input shape for this event.
+ const auditBash = async (input: HookInput): Promise<HookJSONOutput> => {
+ if (input.hook_event_name !== "PreToolUse") return {};
+ const toolInput = input.tool_input as { command?: string };
+ if (toolInput.command?.includes("rm -rf")) {
+ return {
+ hookSpecificOutput: {
+ hookEventName: "PreToolUse",
+ permissionDecision: "deny",
+ permissionDecisionReason: "Destructive command blocked",
+ },
+ };
+ }
+ return {}; // Empty object: allow the tool to proceed
+ };
+
+ // Filesystem hooks from .claude/settings.json run automatically
+ // when settingSources loads them. You can also add programmatic hooks:
+ for await (const message of query({
+ prompt: "Refactor the auth module",
+ options: {
+ settingSources: ["project"], // Loads hooks from .claude/settings.json
+ hooks: {
+ PreToolUse: [{ matcher: "Bash", hooks: [auditBash] }]
+ }
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success") {
+ console.log(message.result);
+ }
+ }
+
###
--- a/cli-reference.md
+++ b/cli-reference.md
@@ -73,7 +73,7 @@
`--debug-file <path>`| Write debug logs to a specific file path. Implicitly enables debug mode. Takes precedence over `CLAUDE_CODE_DEBUG_LOGS_DIR`| `claude --debug-file /tmp/claude-debug.log`
`--disable-slash-commands`| Disable all skills and commands for this session| `claude --disable-slash-commands`
`--disallowedTools`, `--disallowed-tools`| Deny rules. A bare tool name removes the matching tools from the model’s context: `"Edit"` removes Edit, `"*"` removes every tool, and `"mcp__*"` removes every MCP tool. A scoped rule such as `Bash(rm *)` leaves the tool available and denies only matching calls| `"Bash(git log *)" "Bash(git diff *)" "Edit"`
-`--effort`| Set the [effort level](</docs/en/model-config#adjust-effort-level>) for the current session. Options: `low`, `medium`, `high`, `xhigh`, `max`; available levels depend on the model. Overrides the [`effortLevel`](</docs/en/settings#available-settings>) setting for this session and does not persist| `claude --effort high`
+`--effort`| Set the [effort level](</docs/en/model-config#adjust-effort-level>) for the current session. Options: `low`, `medium`, `high`, `xhigh`, `max`, or `ultracode`. Available levels depend on the model. `ultracode` starts the session at `xhigh` effort with [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>) turned on, and requires Claude Code v2.1.203 or later. Overrides the [`effortLevel`](</docs/en/settings#available-settings>) setting for this session and does not persist| `claude --effort high`
`--enable-auto-mode`| Removed in v2.1.111. Auto mode is now in the `Shift+Tab` cycle by default; use `--permission-mode auto` to start in it| `claude --permission-mode auto`
`--exclude-dynamic-system-prompt-sections`| Move per-machine sections from the system prompt (working directory, environment info, memory paths, git-repo flag) into the first user message. Improves prompt-cache reuse across different users and machines running the same task. Only applies with the default system prompt; ignored when `--system-prompt` or `--system-prompt-file` is set. Use with `-p` for scripted, multi-user workloads| `claude -p --exclude-dynamic-system-prompt-sections "query"`
`--exec`| Run a shell command as a PTY-backed background job instead of starting a Claude session. Use with `--bg` to launch from the shell| `claude --bg --exec 'pytest -x'`
--- a/commands.md
+++ b/commands.md
@@ -6,7 +6,7 @@
Commands across a typical workflow
-Most commands are useful at a specific point in a session, from setting up a project to shipping a change. **First session in a repo.** Run `/init` to generate a starter `CLAUDE.md`, then `/memory` to refine it. Use `/mcp` to set up any servers the project needs, ask Claude to create any [subagents](</docs/en/sub-agents>) you want, and run `/permissions` to set your approval rules. **During a task.** `/plan` switches into plan mode before a large change. `/model` and `/effort` adjust which model you’re using and how much reasoning it applies. When the conversation gets long, `/context` shows what’s filling the window and `/compact` summarizes it to free space. Use `/btw` for a quick aside that shouldn’t add to the conversation history. **Run work in parallel.** Claude delegates side tasks to [subagents](</docs/en/sub-agents>), and `/tasks` lists what’s running in the background of the current session. `/background` detaches the whole session to keep running as a [background agent](</docs/en/agent-view>) and frees your terminal. For a large change that spans the codebase, `/batch` decomposes it into independent units and runs each in its own [worktree](</docs/en/worktrees>). See [Run agents in parallel](</docs/en/agents>) for how these approaches relate. **Before you ship.** `/diff` shows what changed, `/code-review` checks the diff for correctness bugs and cleanups and can apply the findings with `--fix`, `/review` gives a read-only review of a GitHub pull request, and `/security-review` checks the diff for security vulnerabilities. `/code-review ultra` runs a multi-agent review in the cloud. **Between sessions.** `/clear` starts fresh on a new task while keeping project memory. `/resume` and `/branch` let you return to or fork an earlier conversation. `/teleport` pulls a web session into this terminal, and `/remote-control` lets you continue this local session from another device. **When something is wrong.** `/rewind` rolls code and conversation back to a checkpoint, or summarizes part of the conversation. `/doctor` and `/debug` diagnose install and runtime issues, and `/feedback` reports a bug with session context attached.
+Most commands are useful at a specific point in a session, from setting up a project to shipping a change. **First session in a repo.** Run `/init` to generate a starter `CLAUDE.md`, then `/memory` to refine it. Use `/mcp` to set up any servers the project needs, ask Claude to create any [subagents](</docs/en/sub-agents>) you want, and run `/permissions` to set your approval rules. **During a task.** `/plan` switches into plan mode before a large change. `/model` and `/effort` adjust which model you’re using and how much reasoning it applies. When the conversation gets long, `/context` shows what’s filling the window and `/compact` summarizes it to free space. Use `/btw` for a quick aside that shouldn’t add to the conversation history. **Run work in parallel.** Claude delegates side tasks to [subagents](</docs/en/sub-agents>), and `/tasks` lists what’s running in the background of the current session. `/background` detaches the whole session to keep running as a [background agent](</docs/en/agent-view>) and frees your terminal. For a large change that spans the codebase, `/batch` decomposes it into independent units and runs each in its own [worktree](</docs/en/worktrees>). See [Run agents in parallel](</docs/en/agents>) for how these approaches relate. **Before you ship.** `/diff` shows what changed, `/code-review` checks the diff for correctness bugs and cleanups and can apply the findings with `--fix`, `/review` gives a fast single-pass, read-only review of a GitHub pull request, `/code-review <level> <pr#>` runs a multi-agent review of one, and `/security-review` checks the diff for security vulnerabilities. `/code-review ultra` runs a multi-agent review in the cloud. **Between sessions.** `/clear` starts fresh on a new task while keeping project memory. `/resume` and `/branch` let you return to or fork an earlier conversation. `/teleport` pulls a web session into this terminal, and `/remote-control` lets you continue this local session from another device. **When something is wrong.** `/rewind` rolls code and conversation back to a checkpoint, or summarizes part of the conversation. `/doctor` and `/debug` diagnose install and runtime issues, and `/feedback` reports a bug with session context attached.
##
@@ -93,7 +93,7 @@
`/remote-env`| Choose the default environment for [cloud agents](</docs/en/claude-code-on-the-web#configure-your-environment>)
`/rename [name]`| Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history
`/resume [session]`| Resume a conversation by ID or name, or open the session picker. As of v2.1.144, [background sessions](</docs/en/agent-view>) appear in the picker marked with `bg`. Alias: `/continue`
-`/review [PR]`| Review a GitHub pull request by number. With no argument, lists open PRs to pick from. For a cloud-based review, see [`/code-review ultra`](</docs/en/ultrareview>)
+`/review [PR]`| Run a fast single-pass, read-only review of a GitHub pull request by number. With no argument, lists open PRs to pick from; text after the PR number becomes additional review instructions. From v2.1.186 through v2.1.201, `/review` instead ran the same multi-agent engine as `/code-review medium`. For a multi-agent review at a chosen effort level, use [`/code-review <level> <pr#>`](</docs/en/code-review#review-a-diff-locally>); for a cloud-based review, see [`/code-review ultra`](</docs/en/ultrareview>)
`/rewind`| Rewind the conversation and/or code to a previous point, or summarize from a selected message. See [checkpointing](</docs/en/checkpointing>). Aliases: `/checkpoint`, `/undo`
`/run`| **[Skill](</docs/en/skills#bundled-skills>).** Launch and drive your project’s app to see a change working, not only passing tests. See [Run and verify your app](</docs/en/skills#run-and-verify-your-app>). Requires Claude Code v2.1.145 or later
`/run-skill-generator`| **[Skill](</docs/en/skills#bundled-skills>).** Teach `/run` and `/verify` how to build, launch, and drive your project’s app from a clean environment by writing a per-project [skill](</docs/en/skills#run-and-verify-your-app>). Requires Claude Code v2.1.145 or later
--- a/cost-tracking.md
+++ b/cost-tracking.md
@@ -66,6 +66,23 @@
// no result message.
console.error(`Session ended with an error: ${error}`);
}
+
+ from claude_agent_sdk import query, ResultMessage
+ import asyncio
+
+ async def main():
+ try:
+ async for message in query(prompt="Summarize this project"):
+ if isinstance(message, ResultMessage):
+ print(f"Total cost: ${message.total_cost_usd or 0}")
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result. If the
+ # failure was an error result, it still carried total_cost_usd and the
+ # branch above has already run; connection or process failures yield
+ # no result message.
+ print(f"Session ended with an error: {error}")
+
+ asyncio.run(main())
##
@@ -186,6 +203,36 @@
console.log(`Total spend: $${totalSpend.toFixed(4)}`);
+ from claude_agent_sdk import query, ResultMessage
+ import asyncio
+
+ async def main():
+ # Track cumulative cost across multiple query() calls
+ total_spend = 0.0
+
+ prompts = [
+ "Read the files in src/ and summarize the architecture",
+ "List all exported functions in src/auth.ts",
+ ]
+
+ for prompt in prompts:
+ try:
+ async for message in query(prompt=prompt):
+ if isinstance(message, ResultMessage):
+ cost = message.total_cost_usd or 0
+ total_spend += cost
+ print(f"This call: ${cost}")
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result. If
+ # the failure was an error result, this call's cost was already
+ # counted; connection or process failures yield no result message.
+ # Continue with the next prompt.
+ print(f"Call failed: {error}")
+
+ print(f"Total spend: ${total_spend:.4f}")
+
+ asyncio.run(main())
+
##
@@ -255,6 +302,20 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ const options = {
+ env: {
+ ...process.env,
+ CLAUDE_CODE_USE_BEDROCK: "1",
+ ENABLE_PROMPT_CACHING_1H: "1",
+ },
+ };
+
+ for await (const message of query({ prompt: "Summarize this project", options })) {
+ console.log(message);
+ }
+
Cache writes with a 1-hour TTL are billed at a higher rate than 5-minute writes, so enabling this trades higher write cost for more cache reads. See [prompt caching pricing](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching>) for details. Claude subscription users already receive 1-hour TTL automatically and do not need to set this variable.
##
Show diff (339 lines)
--- a/custom-tools.md
+++ b/custom-tools.md
@@ -88,6 +88,38 @@
tools=[get_temperature],
)
+ import { tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
+ import { z } from "zod";
+
+ // Define a tool: name, description, input schema, handler
+ const getTemperature = tool(
+ "get_temperature",
+ "Get the current temperature at a location",
+ {
+ latitude: z.number().describe("Latitude coordinate"), // .describe() adds a field description Claude sees
+ longitude: z.number().describe("Longitude coordinate")
+ },
+ async (args) => {
+ // args is typed from the schema: { latitude: number; longitude: number }
+ const response = await fetch(
+ `https://api.open-meteo.com/v1/forecast?latitude=${args.latitude}&longitude=${args.longitude}¤t=temperature_2m&temperature_unit=fahrenheit`
+ );
+ const data: any = await response.json();
+
+ // Return a content array - Claude sees this as the tool result
+ return {
+ content: [{ type: "text", text: `Temperature: ${data.current.temperature_2m}°F` }]
+ };
+ }
+ );
+
+ // Wrap the tool in an in-process MCP server
+ const weatherServer = createSdkMcpServer({
+ name: "weather",
+ version: "1.0.0",
+ tools: [getTemperature]
+ });
+
See the [`tool()`](</docs/en/agent-sdk/typescript#tool>) TypeScript reference or the [`@tool`](</docs/en/agent-sdk/python#tool>) Python reference for full parameter details, including JSON Schema input formats and return value structure.
To make a parameter optional: in TypeScript, add `.default()` to the Zod field. In Python, the dict schema treats every key as required, so leave the parameter out of the schema, mention it in the description string, and read it with `args.get()` in the handler. The `get_precipitation_chance` tool below shows both patterns.
@@ -122,6 +154,21 @@
print(message.result)
asyncio.run(main())
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "What's the temperature in San Francisco?",
+ options: {
+ mcpServers: { weather: weatherServer },
+ allowedTools: ["mcp__weather__get_temperature"]
+ }
+ })) {
+ // "result" is the final message after all tool calls complete
+ if (message.type === "result" && message.subtype === "success") {
+ console.log(message.result);
+ }
+ }
###
@@ -174,6 +221,41 @@
tools=[get_temperature, get_precipitation_chance],
)
+ // Define a second tool for the same server
+ const getPrecipitationChance = tool(
+ "get_precipitation_chance",
+ "Get the hourly precipitation probability for a location",
+ {
+ latitude: z.number(),
+ longitude: z.number(),
+ hours: z
+ .number()
+ .int()
+ .min(1)
+ .max(24)
+ .default(12) // .default() makes the parameter optional
+ .describe("How many hours of forecast to return")
+ },
+ async (args) => {
+ const response = await fetch(
+ `https://api.open-meteo.com/v1/forecast?latitude=${args.latitude}&longitude=${args.longitude}&hourly=precipitation_probability&forecast_days=1`
+ );
+ const data: any = await response.json();
+ const chances = data.hourly.precipitation_probability.slice(0, args.hours);
+
+ return {
+ content: [{ type: "text", text: `Next ${args.hours} hours: ${chances.join("%, ")}%` }]
+ };
+ }
+ );
+
+ // Rebuild the server with both tools in the array
+ const weatherServer = createSdkMcpServer({
+ name: "weather",
+ version: "1.0.0",
+ tools: [getTemperature, getPrecipitationChance]
+ });
+
Every tool in this array consumes context window space on every turn. If you’re defining dozens of tools, see [tool search](</docs/en/agent-sdk/tool-search>) to load them on demand instead.
###
@@ -209,6 +291,14 @@
)
async def get_temperature(args):
return {"content": [{"type": "text", "text": "..."}]}
+
+ tool(
+ "get_temperature",
+ "Get the current temperature at a location",
+ { latitude: z.number(), longitude: z.number() },
+ async (args) => ({ content: [{ type: "text", text: `...` }] }),
+ { annotations: { readOnlyHint: true } } // Lets Claude batch this with other read-only calls
+ );
See `ToolAnnotations` in the [TypeScript](</docs/en/agent-sdk/typescript#toolannotations>) or [Python](</docs/en/agent-sdk/python#toolannotations>) reference.
@@ -303,6 +393,55 @@
"is_error": True,
}
+ tool(
+ "fetch_data",
+ "Fetch data from an API",
+ {
+ endpoint: z.string().url().describe("API endpoint URL")
+ },
+ async (args) => {
+ try {
+ const response = await fetch(args.endpoint);
+
+ if (!response.ok) {
+ // Return the failure as a tool result so Claude can react to it.
+ // isError marks this as a failed call rather than odd-looking data.
+ return {
+ content: [
+ {
+ type: "text",
+ text: `API error: ${response.status} ${response.statusText}`
+ }
+ ],
+ isError: true
+ };
+ }
+
+ const data = await response.json();
+ return {
+ content: [
+ {
+ type: "text",
+ text: JSON.stringify(data, null, 2)
+ }
+ ]
+ };
+ } catch (error) {
+ // Composes the message Claude reads. An uncaught throw would
+ // reach Claude as the raw error message with no context.
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Failed to fetch data: ${error instanceof Error ? error.message : String(error)}`
+ }
+ ],
+ isError: true
+ };
+ }
+ }
+ );
+
##
@@ -352,6 +491,29 @@
]
}
+ tool(
+ "fetch_image",
+ "Fetch an image from a URL and return it to Claude",
+ {
+ url: z.string().url()
+ },
+ async (args) => {
+ const response = await fetch(args.url); // Fetch the image bytes
+ const buffer = Buffer.from(await response.arrayBuffer()); // Read into a Buffer for base64 encoding
+ const mimeType = response.headers.get("content-type") ?? "image/png";
+
+ return {
+ content: [
+ {
+ type: "image",
+ data: buffer.toString("base64"), // Base64-encode the raw bytes
+ mimeType
+ }
+ ]
+ };
+ }
+ );
+
###
@@ -386,6 +548,19 @@
}
]
};
+
+ return {
+ "content": [
+ {
+ "type": "resource",
+ "resource": {
+ "uri": "file:///tmp/report.md", # Label for Claude to reference, not a path the SDK reads
+ "mimeType": "text/markdown",
+ "text": "# Report\n...", # The actual content, inline
+ },
+ }
+ ]
+ }
These block shapes come from the MCP `CallToolResult` type. See the [MCP specification](<https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result>) for the full definition.
@@ -509,6 +684,77 @@
tools=[convert_units],
)
+ import { tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
+ import { z } from "zod";
+
+ const convert = tool(
+ "convert_units",
+ "Convert a value from one unit to another",
+ {
+ unit_type: z.enum(["length", "temperature", "weight"]).describe("Category of unit"),
+ from_unit: z
+ .string()
+ .describe("Unit to convert from, e.g. kilometers, fahrenheit, pounds"),
+ to_unit: z.string().describe("Unit to convert to"),
+ value: z.number().describe("Value to convert")
+ },
+ async (args) => {
+ type Conversions = Record<string, Record<string, (v: number) => number>>;
+
+ const conversions: Conversions = {
+ length: {
+ kilometers_to_miles: (v) => v * 0.621371,
+ miles_to_kilometers: (v) => v * 1.60934,
+ meters_to_feet: (v) => v * 3.28084,
+ feet_to_meters: (v) => v * 0.3048
+ },
+ temperature: {
+ celsius_to_fahrenheit: (v) => (v * 9) / 5 + 32,
+ fahrenheit_to_celsius: (v) => ((v - 32) * 5) / 9,
+ celsius_to_kelvin: (v) => v + 273.15,
+ kelvin_to_celsius: (v) => v - 273.15
+ },
+ weight: {
+ kilograms_to_pounds: (v) => v * 2.20462,
+ pounds_to_kilograms: (v) => v * 0.453592,
+ grams_to_ounces: (v) => v * 0.035274,
+ ounces_to_grams: (v) => v * 28.3495
+ }
+ };
+
+ const key = `${args.from_unit}_to_${args.to_unit}`;
+ const fn = conversions[args.unit_type]?.[key];
+
+ if (!fn) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Unsupported conversion: ${args.from_unit} to ${args.to_unit}`
+ }
+ ],
+ isError: true
+ };
+ }
+
+ const result = fn(args.value);
+ return {
+ content: [
+ {
+ type: "text",
+ text: `${args.value} ${args.from_unit} = ${result.toFixed(4)} ${args.to_unit}`
+ }
+ ]
+ };
+ }
+ );
+
+ const converterServer = createSdkMcpServer({
+ name: "converter",
+ version: "1.0.0",
+ tools: [convert]
+ });
+
Once the server is defined, pass it to `query` the same way as the weather example. This example sends three different prompts in a loop to show the same tool handling different unit types. For each response, it inspects `AssistantMessage` objects (which contain the tool calls Claude made during that turn) and prints each `ToolUseBlock` before printing the final `ResultMessage` text. This lets you see when Claude is using the tool versus answering from its own knowledge.
Python
@@ -547,6 +793,34 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ const prompts = [
+ "Convert 100 kilometers to miles.",
+ "What is 72°F in Celsius?",
+ "How many pounds is 5 kilograms?"
+ ];
+
+ for (const prompt of prompts) {
+ for await (const message of query({
+ prompt,
+ options: {
+ mcpServers: { converter: converterServer },
+ allowedTools: ["mcp__converter__convert_units"]
+ }
+ })) {
+ if (message.type === "assistant") {
+ for (const block of message.message.content) {
+ if (block.type === "tool_use") {
+ console.log(`[tool call] ${block.name}`, block.input);
+ }
+ }
+ } else if (message.type === "result" && message.subtype === "success") {
+ console.log(`Q: ${prompt}\nA: ${message.result}\n`);
+ }
+ }
+ }
+
##
--- a/discover-plugins.md
+++ b/discover-plugins.md
@@ -306,7 +306,12 @@
* type to filter by plugin name or description
* press Enter to open a plugin’s detail view and enable, disable, or uninstall it
-The detail view shows the components the plugin contributes: commands, skills, agents, hooks, MCP servers, and LSP servers. The same inventory is available from the command line with `claude plugin details`. In Claude Code v2.1.187 and later, the Installed tab adds a **Not used recently** group for marketplace plugins you installed yourself but haven’t invoked in at least two weeks, over a span of at least 10 sessions, and the detail view shows a **Last used** line for each plugin. Use these to find plugins that you no longer use but that are still adding startup and context cost, then disable or uninstall them. Plugins that your organization manages or that you load with `--plugin-dir` are never listed as unused, and plugins that contribute an LSP server, theme, output style, monitor, or workflow are also never listed, since those deliver value without an invocation to track. The group and the **Last used** line are both hidden when your organization restricts marketplaces with [`strictKnownMarketplaces`](</docs/en/settings#strictknownmarketplaces>). When you install a plugin that declares dependencies, the install output lists which dependencies were auto-installed alongside it. You can also manage plugins with direct commands. List installed plugins without opening the menu:
+Uninstalling a plugin that a project’s `.claude/settings.json` enables asks which scope you mean: disable it for you alone, which writes an override to your `.claude/settings.local.json` and leaves the plugin installed for the project, or uninstall it for everyone, which removes it from the shared `.claude/settings.json`. Requires Claude Code v2.1.203 or later. Before v2.1.203, the dialog offered only the local disable. The detail view shows the components the plugin contributes: commands, skills, agents, hooks, MCP servers, and LSP servers. The same inventory is available from the command line with `claude plugin details`. The **Installed** tab also collects marketplace plugins you installed yourself but haven’t used in at least two weeks, over a span of at least 10 sessions, under a **Not used recently** header. The detail view shows a **Last used** line for each plugin. Use these to find plugins that still add startup and context cost even though you no longer use them, then disable or uninstall them. Requires Claude Code v2.1.187 or later. Two kinds of plugins are never listed as unused:
+
+ * plugins that your organization manages or that you load with `--plugin-dir`
+ * plugins that contribute a theme, output style, monitor, or workflow, since those deliver value without an invocation to track
+
+The **Not used recently** header and the **Last used** line are both hidden when your organization restricts marketplaces with [`strictKnownMarketplaces`](</docs/en/settings#strictknownmarketplaces>). A plugin’s [language server](</docs/en/plugins#add-lsp-servers-to-your-plugin>) counts as used when it delivers diagnostics or answers a code navigation request, so an LSP plugin whose server is active in your sessions isn’t listed as unused. Before v2.1.203, language server activity couldn’t be counted as use, so plugins that contribute an LSP server were exempt from the group entirely, the same way theme and output style plugins still are. When you install a plugin that declares dependencies, the install output lists which dependencies were auto-installed alongside it. You can also manage plugins with direct commands. List installed plugins without opening the menu:
/plugin list
--- a/env-vars.md
+++ b/env-vars.md
@@ -117,6 +117,7 @@
`ANTHROPIC_DEFAULT_SONNET_MODEL_NAME`| See [Model configuration](</docs/en/model-config#customize-pinned-model-display-and-capabilities>)
`ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES`| See [Model configuration](</docs/en/model-config#customize-pinned-model-display-and-capabilities>)
`ANTHROPIC_FOUNDRY_API_KEY`| API key for Microsoft Foundry authentication (see [Microsoft Foundry](</docs/en/microsoft-foundry>))
+`ANTHROPIC_FOUNDRY_AUTH_TOKEN`| Bearer token for Microsoft Foundry authentication, such as a Microsoft Entra access token. Claude Code sends it as the `Authorization: Bearer` header. Takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` and over the Azure default credential chain. See [Microsoft Foundry](</docs/en/microsoft-foundry>). Requires Claude Code v2.1.203 or later
`ANTHROPIC_FOUNDRY_BASE_URL`| Full base URL for the Microsoft Foundry resource (for example, `https://my-resource.services.ai.azure.com/anthropic`). Alternative to `ANTHROPIC_FOUNDRY_RESOURCE` (see [Microsoft Foundry](</docs/en/microsoft-foundry>))
`ANTHROPIC_FOUNDRY_RESOURCE`| Microsoft Foundry resource name (for example, `my-resource`). Required if `ANTHROPIC_FOUNDRY_BASE_URL` is not set (see [Microsoft Foundry](</docs/en/microsoft-foundry>))
`ANTHROPIC_MODEL`| Name of the model setting to use (see [Model Configuration](</docs/en/model-config#environment-variables>))
@@ -226,7 +227,7 @@
`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`| Maximum number of read-only tools and subagents that can execute in parallel (default: 10). Higher values increase parallelism but consume more resources
`CLAUDE_CODE_MAX_TURNS`| Cap the number of agentic turns when no explicit limit is passed. Equivalent to passing [`--max-turns`](</docs/en/cli-reference#cli-flags>), which takes precedence when both are set. A value that is not a positive integer is rejected at startup with an error rather than treated as no cap
`CLAUDE_CODE_MCP_ALLOWLIST_ENV`| Set to `1` to spawn stdio MCP servers with only a safe baseline environment plus the server’s configured `env`, instead of inheriting your shell environment
-`CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`| Idle timeout in milliseconds for remote MCP tool calls (default: 300000, or 5 minutes). When an HTTP, SSE, WebSocket, or [claude.ai connector](</docs/en/mcp#use-mcp-servers-from-claude-ai>) MCP server sends no response and no progress notification for this long, the tool call aborts with an error instead of waiting for the overall `MCP_TOOL_TIMEOUT`. Set to `0` to disable the idle check. Values below 1000 are raised to one second, and the value is capped at the effective `MCP_TOOL_TIMEOUT`. Does not apply to stdio or IDE servers. Requires Claude Code v2.1.187 or later
+`CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`| Idle timeout in milliseconds for MCP tool calls. When a stdio, HTTP, SSE, WebSocket, or [claude.ai connector](</docs/en/mcp#use-mcp-servers-from-claude-ai>) MCP server sends no response and no progress notification for this long, the tool call aborts with an error instead of waiting for the overall `MCP_TOOL_TIMEOUT`. Overrides the per-transport defaults of 300000 (5 minutes) for network servers and 1800000 (30 minutes) for stdio servers. Set to `0` to disable the idle check. Values below 1000 are raised to one second, and the value is capped at the effective `MCP_TOOL_TIMEOUT`. A per-server `timeout` in `.mcp.json` of at least 1000 raises that server’s idle window to at least the `timeout` value. Doesn’t apply to IDE servers or SDK in-process servers. Requires Claude Code v2.1.187 or later. Before v2.1.203, stdio servers were exempt from the idle timeout
`CLAUDE_CODE_NATIVE_CURSOR`| Set to `1` to show the terminal’s own cursor at the input caret instead of a drawn block. The cursor respects the terminal’s blink, shape, and focus settings
`CLAUDE_CODE_NEW_INIT`| Set to `1` to make `/init` run an interactive setup flow. The flow asks which files to generate, including CLAUDE.md, skills, and hooks, before exploring the codebase and writing them. Without this variable, `/init` generates a CLAUDE.md automatically without prompting
`CLAUDE_CODE_NO_FLICKER`| Set to `1` to enable [fullscreen rendering](</docs/en/fullscreen>), a research preview that reduces flicker and keeps memory flat in long conversations. Equivalent to the [`tui`](</docs/en/settings#available-settings>) setting; you can also switch with `/tui fullscreen`
@@ -266,7 +267,7 @@
`CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT`| Set to `1` to use a shorter system prompt and abbreviated tool descriptions on any model. Set to `0`, `false`, `no`, or `off` to opt out even on models where the experiment or server configuration would otherwise enable it. The full tool set, hooks, MCP servers, and CLAUDE.md discovery remain enabled
`CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH`| Skip client-side authentication for [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), for gateways that sign requests themselves
`CLAUDE_CODE_SKIP_BEDROCK_AUTH`| Skip AWS authentication for Amazon Bedrock (for example, when using an LLM gateway)
-`CLAUDE_CODE_SKIP_FOUNDRY_AUTH`| Skip Azure authentication for Microsoft Foundry. For a gateway, set the credential in `ANTHROPIC_FOUNDRY_API_KEY` instead; without an API key this variable leaves the Microsoft Foundry client unable to send requests
+`CLAUDE_CODE_SKIP_FOUNDRY_AUTH`| Skip Azure authentication for Microsoft Foundry, for a proxy or gateway that injects its own `Authorization` header. Claude Code sends requests without an Azure credential and preserves the `Authorization` header you supply, for example through `ANTHROPIC_CUSTOM_HEADERS`. Ignored when `ANTHROPIC_FOUNDRY_API_KEY` or `ANTHROPIC_FOUNDRY_AUTH_TOKEN` is set. Before v2.1.203, this variable left the Microsoft Foundry client unable to send requests unless an API key was also set
`CLAUDE_CODE_SKIP_MANTLE_AUTH`| Skip AWS authentication for Amazon Bedrock Mantle (for example, when using an LLM gateway)
`CLAUDE_CODE_SKIP_PROMPT_HISTORY`| Set to `1` to skip writing prompt history and session transcripts to disk. Sessions started with this variable set do not appear in `--resume`, `--continue`, or up-arrow history. Useful for ephemeral scripted sessions
`CLAUDE_CODE_SKIP_VERTEX_AUTH`| Skip Google authentication for Google Cloud’s Agent Platform (for example, when using an LLM gateway)
@@ -343,7 +344,7 @@
`MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE`| Maximum number of remote MCP servers (HTTP/SSE) to connect in parallel during startup (default: 20)
`MCP_SERVER_CONNECTION_BATCH_SIZE`| Maximum number of local MCP servers (stdio) to connect in parallel during startup (default: 3)
`MCP_TIMEOUT`| Timeout in milliseconds for MCP server startup (default: 30000, or 30 seconds)
-`MCP_TOOL_TIMEOUT`| Timeout in milliseconds for MCP tool execution (default: 100000000, about 28 hours). A per-server `timeout` field in `.mcp.json` overrides this for that server. For the env variable, values below 1000 are floored to one second; for the per-server field, values below 1000 are ignored
+`MCP_TOOL_TIMEOUT`| Timeout in milliseconds for MCP tool execution (default: 100000000, about 28 hours). A per-server `timeout` field in `.mcp.json` overrides this for that server. A per-server `timeout` of at least 1000 also sets the minimum idle window for that server’s tool calls, so `CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT` never aborts them sooner; this floor requires Claude Code v2.1.203 or later. For the env variable, values below 1000 are floored to one second; for the per-server field, values below 1000 are ignored
`NO_PROXY`| List of domains and IPs to which requests will be directly issued, bypassing proxy
`OTEL_LOG_ASSISTANT_RESPONSES`| Set to `1` to include the model’s response text on `assistant_response` OpenTelemetry log events. When unset, the value of `OTEL_LOG_USER_PROMPTS` is used instead. Set to `0` to keep responses redacted even when `OTEL_LOG_USER_PROMPTS` is set. Requires Claude Code v2.1.193 or later. See [Monitoring](</docs/en/monitoring-usage#assistant-response-event>)
`OTEL_LOG_RAW_API_BODIES`| Emit Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB, or `file:<dir>` to write untruncated bodies to disk and emit a `body_ref` path instead. Disabled by default; bodies include the entire conversation history. See [Monitoring](</docs/en/monitoring-usage#api-request-body-event>)
--- a/errors.md
+++ b/errors.md
@@ -59,6 +59,7 @@
`max_tokens must be greater than thinking.budget_tokens`| Request errors
`API Error: 400 due to tool use concurrency issues`| Request errors
`Claude Code is unable to respond to this request, which appears to violate our Usage Policy`| Request errors
+`<model> has safety measures that flagged this message for a cybersecurity topic`| Request errors
`Installation was killed before it could finish (exit code 137)`| Installation errors
`The connection dropped while downloading the update`| Installation errors
`--bg and --print conflict`| Command-line errors
@@ -876,11 +877,34 @@
API Error: Claude Code is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup). Please double press esc to edit your last message or start a new session for Claude Code to assist with a different task.
-The check evaluates the full conversation, not only your latest prompt, so sending a new message in the same session usually re-triggers the same refusal. The same applies after exiting and reopening the session with `--continue` or `--resume`, since the transcript on disk still contains the triggering content. **What to do:**
+The check evaluates the full conversation, not only your latest prompt, so sending a new message in the same session usually re-triggers the same refusal. The same applies after exiting and reopening the session with `--continue` or `--resume`, since the transcript on disk still contains the triggering content. On [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), and [Microsoft Foundry](</docs/en/microsoft-foundry>), this message also covers requests the model’s safety measures flagged as a cybersecurity topic. See Safety measures flagged a cybersecurity topic. **What to do:**
* Press Esc twice or run `/rewind` to step back to a checkpoint before the turn that triggered the refusal, then rephrase or take a different approach. See [Checkpointing](</docs/en/checkpointing>).
* If you can’t identify which turn caused it, run `/clear` to start a fresh conversation in the same project. Your previous conversation is preserved on disk and remains available in `/resume`.
* In [non-interactive mode](</docs/en/headless>) (`-p`), where rewind is unavailable, retry with a rephrased prompt in a new session without `--continue`. Policy checks vary by model, so switching to a different model with `--model` may also resolve the refusal in some cases.
+
+###
+
+
+
+Safety measures flagged a cybersecurity topic
+
+The model’s safety measures flagged content in the conversation as a cybersecurity topic. The message names the model that flagged the request:
+
+ API Error: Opus 4.8 has safety measures that flagged this message for a cybersecurity topic. To learn about the Cyber Verification Program and apply for access, visit our help center: https://support.claude.com/en/articles/14604842-real-time-cyber-safeguards-on-claude.
+
+ If you were not engaging in a cybersecurity topic, please send feedback via /feedback.
+
+The message links to the [Cyber Verification Program](<https://support.claude.com/en/articles/14604842-real-time-cyber-safeguards-on-claude>), which grants access for legitimate cybersecurity work. The safeguard itself is server-side and predates v2.1.203; this release changed only the wording of the message and the page it links to. What you see depends on your provider and mode:
+
+ * On [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), and [Microsoft Foundry](</docs/en/microsoft-foundry>), a cybersecurity flag produces the Usage Policy refusal message instead.
+ * [Non-interactive mode](</docs/en/headless>) omits the `/feedback` sentence.
+
+Before v2.1.203, the message read `<model>'s safeguards flagged this message for a cybersecurity topic. If your work requires this access, you can apply for an exemption:` followed by an exemption form link. **What to do:**
+
+ * If your work requires this content, apply for access through the [Cyber Verification Program](<https://support.claude.com/en/articles/14604842-real-time-cyber-safeguards-on-claude>)
+ * If your request wasn’t about a cybersecurity topic, run `/feedback` to report the false positive
+ * To keep working in the same session, press Esc twice or run `/rewind` to step back to a checkpoint before the turn that triggered the flag, then take a different approach. See [Checkpointing](</docs/en/checkpointing>).
##
Show diff (332 lines)
--- a/file-checkpointing.md
+++ b/file-checkpointing.md
@@ -87,6 +87,51 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ async function main() {
+ // Step 1: Enable checkpointing
+ const opts = {
+ enableFileCheckpointing: true,
+ permissionMode: "acceptEdits" as const, // Auto-accept file edits without prompting
+ extraArgs: { "replay-user-messages": null } // Required to receive checkpoint UUIDs in the response stream
+ };
+
+ const response = query({
+ prompt: "Refactor the authentication module",
+ options: opts
+ });
+
+ let checkpointId: string | undefined;
+ let sessionId: string | undefined;
+
+ // Step 2: Capture checkpoint UUID from the first user message
+ for await (const message of response) {
+ if (message.type === "user" && message.uuid && !checkpointId) {
+ checkpointId = message.uuid;
+ }
+ if ("session_id" in message && !sessionId) {
+ sessionId = message.session_id;
+ }
+ }
+
+ // Step 3: Later, rewind by resuming the session with an empty prompt
+ if (checkpointId && sessionId) {
+ const rewindQuery = query({
+ prompt: "", // Empty prompt to open the connection
+ options: { ...opts, resume: sessionId }
+ });
+
+ for await (const msg of rewindQuery) {
+ await rewindQuery.rewindFiles(checkpointId);
+ break;
+ }
+ console.log(`Rewound to checkpoint: ${checkpointId}`);
+ }
+ }
+
+ main();
+
1
Enable checkpointing
@@ -110,6 +155,15 @@
async with ClaudeSDKClient(options) as client:
await client.query("Refactor the authentication module")
+
+ const response = query({
+ prompt: "Refactor the authentication module",
+ options: {
+ enableFileCheckpointing: true,
+ permissionMode: "acceptEdits" as const,
+ extraArgs: { "replay-user-messages": null }
+ }
+ });
2
@@ -132,6 +186,20 @@
if isinstance(message, ResultMessage):
session_id = message.session_id
+ let checkpointId: string | undefined;
+ let sessionId: string | undefined;
+
+ for await (const message of response) {
+ // Capture the first user message UUID as the checkpoint
+ if (message.type === "user" && message.uuid && !checkpointId) {
+ checkpointId = message.uuid;
+ }
+ // Capture session ID from any message that has it
+ if ("session_id" in message) {
+ sessionId = message.session_id;
+ }
+ }
+
3
Rewind files
@@ -150,6 +218,16 @@
await client.rewind_files(checkpoint_id)
break
+ const rewindQuery = query({
+ prompt: "", // Empty prompt to open the connection
+ options: { ...opts, resume: sessionId }
+ });
+
+ for await (const msg of rewindQuery) {
+ await rewindQuery.rewindFiles(checkpointId);
+ break;
+ }
+
If you capture the session ID and checkpoint ID, you can also rewind from the CLI. This command requires the `claude` executable, which comes from [installing Claude Code](</docs/en/setup>) and is not installed by the SDK package. The SDK enables checkpointing for you, but when you run `claude -p` directly you must set the `CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING` environment variable:
CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true claude -p --resume <session-id> --rewind-files <checkpoint-uuid>
@@ -205,6 +283,39 @@
break
asyncio.run(main())
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ async function main() {
+ const response = query({
+ prompt: "Refactor the authentication module",
+ options: {
+ enableFileCheckpointing: true,
+ permissionMode: "acceptEdits" as const,
+ extraArgs: { "replay-user-messages": null }
+ }
+ });
+
+ let safeCheckpoint: string | undefined;
+
+ for await (const message of response) {
+ // Update checkpoint before each agent turn starts
+ // This overwrites the previous checkpoint. Only keep the latest
+ if (message.type === "user" && message.uuid) {
+ safeCheckpoint = message.uuid;
+ }
+
+ // Decide when to revert based on your own logic
+ // For example: error detection, validation failure, or user input
+ if (yourRevertCondition && safeCheckpoint) {
+ await response.rewindFiles(safeCheckpoint);
+ // Exit the loop after rewinding, files are restored
+ break;
+ }
+ }
+ }
+
+ main();
###
@@ -274,6 +385,61 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Store checkpoint metadata for better tracking
+ interface Checkpoint {
+ id: string;
+ description: string;
+ timestamp: Date;
+ }
+
+ async function main() {
+ const opts = {
+ enableFileCheckpointing: true,
+ permissionMode: "acceptEdits" as const,
+ extraArgs: { "replay-user-messages": null }
+ };
+
+ const response = query({
+ prompt: "Refactor the authentication module",
+ options: opts
+ });
+
+ const checkpoints: Checkpoint[] = [];
+ let sessionId: string | undefined;
+
+ for await (const message of response) {
+ if (message.type === "user" && message.uuid) {
+ checkpoints.push({
+ id: message.uuid,
+ description: `After turn ${checkpoints.length + 1}`,
+ timestamp: new Date()
+ });
+ }
+ if ("session_id" in message && !sessionId) {
+ sessionId = message.session_id;
+ }
+ }
+
+ // Later: rewind to any checkpoint by resuming the session
+ if (checkpoints.length > 0 && sessionId) {
+ const target = checkpoints[0]; // Pick any checkpoint
+ const rewindQuery = query({
+ prompt: "", // Empty prompt to open the connection
+ options: { ...opts, resume: sessionId }
+ });
+
+ for await (const msg of rewindQuery) {
+ await rewindQuery.rewindFiles(target.id);
+ break;
+ }
+ console.log(`Rewound to: ${target.description}`);
+ }
+ }
+
+ main();
+
##
@@ -305,6 +471,25 @@
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
+
+ export function add(a: number, b: number): number {
+ return a + b;
+ }
+
+ export function subtract(a: number, b: number): number {
+ return a - b;
+ }
+
+ export function multiply(a: number, b: number): number {
+ return a * b;
+ }
+
+ export function divide(a: number, b: number): number {
+ if (b === 0) {
+ throw new Error("Cannot divide by zero");
+ }
+ return a / b;
+ }
2
@@ -376,6 +561,77 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+ import * as readline from "readline";
+
+ async function main() {
+ // Configure the SDK with checkpointing enabled
+ // - enableFileCheckpointing: Track file changes for rewinding
+ // - permissionMode: Auto-accept file edits without prompting
+ // - extraArgs: Required to receive user message UUIDs in the stream
+ const opts = {
+ enableFileCheckpointing: true,
+ permissionMode: "acceptEdits" as const,
+ extraArgs: { "replay-user-messages": null }
+ };
+
+ let sessionId: string | undefined; // Store the session ID for resuming
+ let checkpointId: string | undefined; // Store the user message UUID for rewinding
+
+ console.log("Running agent to add doc comments to utils.ts...\n");
+
+ // Run the agent and capture checkpoint data from the response stream
+ const response = query({
+ prompt: "Add doc comments to utils.ts",
+ options: opts
+ });
+
+ for await (const message of response) {
+ // Capture the first user message UUID - this is our restore point
+ if (message.type === "user" && message.uuid && !checkpointId) {
+ checkpointId = message.uuid;
+ }
+ // Capture the session ID so we can resume later
+ if ("session_id" in message) {
+ sessionId = message.session_id;
+ }
+ }
+
+ console.log("Done! Open utils.ts to see the added doc comments.\n");
+
+ // Ask the user if they want to rewind the changes
+ if (checkpointId && sessionId) {
+ const rl = readline.createInterface({
+ input: process.stdin,
+ output: process.stdout
+ });
+
+ const answer = await new Promise<string>((resolve) => {
+ rl.question("Rewind to remove the doc comments? (y/n): ", resolve);
+ });
+ rl.close();
+
+ if (answer.toLowerCase() === "y") {
+ // Resume the session with an empty prompt, then rewind
+ const rewindQuery = query({
+ prompt: "", // Empty prompt opens the connection
+ options: { ...opts, resume: sessionId }
+ });
+
+ for await (const msg of rewindQuery) {
+ await rewindQuery.rewindFiles(checkpointId); // Restore files
+ break;
+ }
+
+ console.log("\n✓ File restored! Open utils.ts to verify the doc comments are gone.");
+ } else {
+ console.log("\nKept the modified file.");
+ }
+ }
+ }
+
+ main();
+
This example demonstrates the complete checkpointing workflow:
1. **Enable checkpointing** : configure the SDK with `enable_file_checkpointing=True` and `permission_mode="acceptEdits"` to auto-approve file edits
@@ -487,6 +743,17 @@
await client.rewind_files(checkpoint_id)
break
+ // Resume session with empty prompt, then rewind
+ const rewindQuery = query({
+ prompt: "",
+ options: { ...opts, resume: sessionId }
+ });
+
+ for await (const msg of rewindQuery) {
+ await rewindQuery.rewindFiles(checkpointId);
+ break;
+ }
+
##
--- a/hosting.md
+++ b/hosting.md
@@ -15,6 +15,8 @@
Python
query({ prompt, options: { cwd: "/work/session-a" } })
+
+ query(prompt=prompt, options=ClaudeAgentOptions(cwd="/work/session-a"))
###
@@ -87,6 +89,17 @@
})) {
// ...
}
+
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async for message in query(
+ prompt=user_input,
+ options=ClaudeAgentOptions(
+ resume=session_id, # looked up from your database by user
+ session_store=session_store, # S3, Redis, Postgres, or your own adapter
+ ),
+ ):
+ ...
See [Session storage](</docs/en/agent-sdk/session-storage>) for the full `SessionStore` interface and reference adapters.
@@ -271,6 +284,21 @@
// ...
}
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async for message in query(
+ prompt=prompt,
+ options=ClaudeAgentOptions(
+ cwd=tenant_dir,
+ setting_sources=[],
+ env={
+ "CLAUDE_CONFIG_DIR": config_dir,
+ "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1",
+ },
+ ),
+ ):
+ ...
+
For per-tenant network controls, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>).
##
--- a/llm-gateway-connect.md
+++ b/llm-gateway-connect.md
@@ -256,6 +256,13 @@
},
})
+ options = ClaudeAgentOptions(
+ env={
+ "ANTHROPIC_BASE_URL": "https://llm-gateway.example.com",
+ "ANTHROPIC_AUTH_TOKEN": os.environ["GATEWAY_KEY"],
+ }
+ )
+
###
@@ -348,7 +355,7 @@
Route to a cloud provider through a gateway
-These configurations point Claude Code at a gateway through a provider-specific base URL variable in place of `ANTHROPIC_BASE_URL`. Amazon Bedrock and Google Cloud’s Agent Platform gateways accept those providers’ native request formats; Microsoft Foundry and Claude Platform on AWS gateways accept the Anthropic Messages format and differ only in which base URL variable reaches them. Use one only if your gateway team specifically named Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or the Claude Platform on AWS. If the verification request above returned JSON, you can skip this section. Set the block for the provider your gateway team named. The skip-auth variables tell Claude Code not to sign requests with provider credentials, since the gateway holds those. If the gateway needs its own token, add `ANTHROPIC_AUTH_TOKEN` after the block, except for Microsoft Foundry, which uses `ANTHROPIC_FOUNDRY_API_KEY` as shown.
+These configurations point Claude Code at a gateway through a provider-specific base URL variable in place of `ANTHROPIC_BASE_URL`. Amazon Bedrock and Google Cloud’s Agent Platform gateways accept those providers’ native request formats; Microsoft Foundry and Claude Platform on AWS gateways accept the Anthropic Messages format and differ only in which base URL variable reaches them. Use one only if your gateway team specifically named Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or the Claude Platform on AWS. If the verification request above returned JSON, you can skip this section. Set the block for the provider your gateway team named. The skip-auth variables tell Claude Code not to sign requests with provider credentials, since the gateway holds those. If the gateway needs its own token, add `ANTHROPIC_AUTH_TOKEN` after the block, except for Microsoft Foundry, which uses `ANTHROPIC_FOUNDRY_API_KEY` as shown. A Microsoft Foundry gateway that expects a bearer token can use [`ANTHROPIC_FOUNDRY_AUTH_TOKEN`](</docs/en/env-vars>) instead; it takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` when both are set. `ANTHROPIC_FOUNDRY_AUTH_TOKEN` requires Claude Code v2.1.203 or later.
####
@@ -396,7 +403,7 @@
Microsoft Foundry
-Put the gateway’s credential in `ANTHROPIC_FOUNDRY_API_KEY`; it is sent to the gateway as the `x-api-key` header. `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` doesn’t apply here: without an API key, the Microsoft Foundry client fails every request before it leaves the machine.
+Put the gateway’s credential in `ANTHROPIC_FOUNDRY_API_KEY`; it is sent to the gateway as the `x-api-key` header. A gateway that expects a bearer token can take [`ANTHROPIC_FOUNDRY_AUTH_TOKEN`](</docs/en/env-vars>) instead. Claude Code sends that value as the `Authorization: Bearer` header, and it takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` when both are set. Requires Claude Code v2.1.203 or later. For a gateway that injects its own `Authorization` header, set `CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1` and leave both credential variables unset. Claude Code then sends requests without an Azure credential and preserves the `Authorization` header you supply, for example through `ANTHROPIC_CUSTOM_HEADERS`. Before v2.1.203, `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` without an API key left the Microsoft Foundry client unable to send requests.
* Bash or Zsh
--- a/mcp.md
+++ b/mcp.md
@@ -97,7 +97,7 @@
Option 3: Add a local stdio server
-Stdio servers run as local processes on your machine. They’re ideal for tools that need direct system access or custom scripts. Claude Code sets `CLAUDE_PROJECT_DIR` in the spawned server’s environment to the project root, so your server can resolve project-relative paths without depending on the working directory. This is the same directory hooks receive in their `CLAUDE_PROJECT_DIR` variable. Read it from inside your server process, for example `process.env.CLAUDE_PROJECT_DIR` in Node or `os.environ["CLAUDE_PROJECT_DIR"]` in Python. Your server can also call the MCP `roots/list` request, which returns the directory Claude Code was launched from. This variable is set in the server’s environment, not in Claude Code’s own environment, so referencing it via `${VAR}` expansion in a project- or user-scoped `.mcp.json` `command` or `args` requires a default such as `${CLAUDE_PROJECT_DIR:-.}`. Plugin-provided MCP configurations substitute `${CLAUDE_PROJECT_DIR}` directly and don’t need the default.
+Stdio servers run as local processes on your machine. They’re ideal for tools that need direct system access or custom scripts. Claude Code sets `CLAUDE_PROJECT_DIR` in the spawned server’s environment to the project root, so your server can resolve project-relative paths without depending on the working directory. This is the same directory hooks receive in their `CLAUDE_PROJECT_DIR` variable. Read it from inside your server process, for example `process.env.CLAUDE_PROJECT_DIR` in Node or `os.environ["CLAUDE_PROJECT_DIR"]` in Python. `CLAUDE_PROJECT_DIR` is the stable project root and doesn’t change when you add or remove working directories mid-session. A server that limits its own filesystem access to a set of allowed directories should implement the MCP `roots/list` request instead. Claude Code answers `roots/list` with the session’s launch directory plus every [additional working directory](</docs/en/permissions#working-directories>) you’ve granted with `--add-dir`, `/add-dir`, or the `additionalDirectories` setting. Claude Code sends `notifications/roots/list_changed` when that set changes. Before v2.1.203, `roots/list` returned only the launch directory and Claude Code didn’t send `notifications/roots/list_changed`. This variable is set in the server’s environment, not in Claude Code’s own environment, so referencing it via `${VAR}` expansion in a project- or user-scoped `.mcp.json` `command` or `args` requires a default such as `${CLAUDE_PROJECT_DIR:-.}`. Plugin-provided MCP configurations substitute `${CLAUDE_PROJECT_DIR}` directly and don’t need the default.
# Basic syntax
claude mcp add [options] <name> -- <command> [args...]
@@ -192,7 +192,7 @@
* Claude Code displays a warning when MCP tool output exceeds 10,000 tokens. To increase this limit, set the `MAX_MCP_OUTPUT_TOKENS` environment variable (for example, `MAX_MCP_OUTPUT_TOKENS=50000`)
* Use `/mcp` to authenticate with remote servers that require OAuth 2.0 authentication
-The per-server `timeout` is a hard wall-clock limit per tool call, and progress notifications from the server don’t extend it. Values below 1000 are ignored and fall through to `MCP_TOOL_TIMEOUT`, or to its default of about 28 hours when that variable is unset. Before v2.1.162, values below 1000 were floored to one second instead. For HTTP and SSE servers, the per-request fetch first-byte budget has a 60-second minimum. As of v2.1.187, a tool call to a remote HTTP, SSE, WebSocket, or claude.ai connector server that sends no response and no progress notification for 5 minutes aborts with an error instead of waiting for the wall-clock limit. Set the [`CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`](</docs/en/env-vars>) environment variable in milliseconds to change the idle window, or set it to `0` to disable the check. Stdio servers are local processes and are not subject to the idle timeout.
+The per-server `timeout` is a hard wall-clock limit per tool call, and progress notifications from the server don’t extend it. Values below 1000 are ignored and fall through to `MCP_TOOL_TIMEOUT`, or to its default of about 28 hours when that variable is unset. Before v2.1.162, values below 1000 were floored to one second instead. A per-server `timeout` of at least 1000 also acts as a floor on the idle timeout described below: Claude Code never aborts that server’s tool calls for idleness sooner than the per-server `timeout`. Requires Claude Code v2.1.203 or later. For HTTP and SSE servers, the per-request fetch first-byte budget has a 60-second minimum. A tool call to an MCP server that sends no response and no progress notification for the idle window aborts with an error instead of waiting for the wall-clock limit. The idle timeout requires Claude Code v2.1.187 or later. It applies to every server type except IDE servers and SDK in-process servers. The idle window defaults to five minutes for HTTP, SSE, WebSocket, and claude.ai connector servers, and to 30 minutes for stdio servers. Before v2.1.203, stdio servers were exempt from the idle timeout. Set the [`CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`](</docs/en/env-vars>) environment variable in milliseconds to change the idle window, or set it to `0` to disable the check.
###
--- a/mcp-quickstart.md
+++ b/mcp-quickstart.md
@@ -291,7 +291,7 @@
Claude Code didn’t find any servers for the current directory. The most common causes:
* You ran `claude mcp add` from a different project. Local-scoped servers are tied to the project where you added them: the repository root, or the exact directory if you weren’t in a git repository. Re-add the server from the project you’re in now, or add it with `--scope user` so it isn’t tied to a project.
- * You edited a configuration file at the wrong path. The correct files are `~/.claude.json` and `<project>/.mcp.json`. Claude Code doesn’t read paths such as `~/.claude/config/mcp.json`, `~/.claude/mcp.json`, or `%APPDATA%\Claude\mcp.json`.
+ * You edited a configuration file at the wrong path. The correct files are `~/.claude.json` and `<project>/.mcp.json`. Claude Code doesn’t read paths such as `~/.claude/.mcp.json`, `~/.claude/config/mcp.json`, `~/.claude/mcp.json`, or `%APPDATA%\Claude\mcp.json`. For user-scoped servers, run `claude mcp add --scope user`, which writes to the `mcpServers` key in `~/.claude.json`; for project-scoped servers, edit `.mcp.json` at the project root.
Status shows Failed to connect or Connection error
--- a/microsoft-foundry.md
+++ b/microsoft-foundry.md
@@ -39,7 +39,7 @@
2\. Configure Azure credentials
-Claude Code supports two authentication methods for Microsoft Foundry. Choose the method that best fits your security requirements. **Option A: API key authentication**
+Claude Code supports three authentication methods for Microsoft Foundry. Choose the method that best fits your security requirements. **Option A: API key authentication**
1. Navigate to your resource in the Microsoft Foundry portal
2. Go to the **Endpoints and keys** section
@@ -48,9 +48,15 @@
export ANTHROPIC_FOUNDRY_API_KEY=your-azure-api-key
-**Option B: Microsoft Entra ID authentication** When `ANTHROPIC_FOUNDRY_API_KEY` is not set, Claude Code automatically uses the Azure SDK [default credential chain](<https://learn.microsoft.com/en-us/azure/developer/javascript/sdk/authentication/credential-chains#defaultazurecredential-overview>). This supports a variety of methods for authenticating local and remote workloads. On local environments, you commonly may use the Azure CLI:
+**Option B: Microsoft Entra ID authentication** When neither `ANTHROPIC_FOUNDRY_API_KEY` nor `ANTHROPIC_FOUNDRY_AUTH_TOKEN` is set, Claude Code automatically uses the Azure SDK [default credential chain](<https://learn.microsoft.com/en-us/azure/developer/javascript/sdk/authentication/credential-chains#defaultazurecredential-overview>). This supports a variety of methods for authenticating local and remote workloads. On local environments, you commonly may use the Azure CLI:
az login
+
+**Option C: Bearer token authentication** Claude Code sends the value of `ANTHROPIC_FOUNDRY_AUTH_TOKEN` on every request as the `Authorization: Bearer` header. Use this option when another process, such as a host application or a sign-in script, has already obtained an access token for you. Requires Claude Code v2.1.203 or later. Set the variable to a bearer token that Microsoft Entra ID issued for your resource:
+
+ export ANTHROPIC_FOUNDRY_AUTH_TOKEN=your-entra-access-token
+
+`ANTHROPIC_FOUNDRY_AUTH_TOKEN` takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` and over the default credential chain.
When using Microsoft Foundry, the `/logout` command is unavailable since authentication is handled through Azure credentials.
--- a/migration-guide.md
+++ b/migration-guide.md
@@ -164,6 +164,29 @@
}
});
+ # BEFORE (v0.0.x) - Used Claude Code's system prompt by default
+ async for message in query(prompt="Hello"):
+ print(message)
+
+ # AFTER (v0.1.0) - Uses minimal system prompt by default
+ # To get the old behavior, explicitly request Claude Code's preset:
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async for message in query(
+ prompt="Hello",
+ options=ClaudeAgentOptions(
+ system_prompt={"type": "preset", "preset": "claude_code"} # Use the preset
+ ),
+ ):
+ print(message)
+
+ # Or use a custom system prompt:
+ async for message in query(
+ prompt="Hello",
+ options=ClaudeAgentOptions(system_prompt="You are a helpful coding assistant"),
+ ):
+ print(message)
+
**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code’s CLI-focused instructions.
###
@@ -194,6 +217,23 @@
settingSources: ["project"] // Only project settings
}
});
+
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async for message in query(
+ prompt="Hello",
+ options=ClaudeAgentOptions(setting_sources=[]), # No filesystem settings loaded
+ ):
+ print(message)
+
+ # Or load only specific sources:
+ async for message in query(
+ prompt="Hello",
+ options=ClaudeAgentOptions(
+ setting_sources=["project"] # Only project settings
+ ),
+ ):
+ print(message)
Isolation is especially important for CI/CD pipelines, deployed applications, test environments, and multi-tenant systems where local customizations should not leak in.
--- a/model-config.md
+++ b/model-config.md
@@ -365,7 +365,13 @@
Sonnet 5, Opus 4.8, and Opus 4.7| `low`, `medium`, `high`, `xhigh`, `max`
Opus 4.6 and Sonnet 4.6| `low`, `medium`, `high`, `max`
-If you set a level the active model does not support, Claude Code falls back to the highest supported level at or below the one you set. For example, `xhigh` runs as `high` on Opus 4.6. Your organization can also cap which levels are available for a model; see Organization effort limits. The default effort is `high` on Fable 5, Sonnet 5, Opus 4.8, Opus 4.6, and Sonnet 4.6, and `xhigh` on Opus 4.7. When you first run Fable 5, Opus 4.8, or Opus 4.7, Claude Code applies that model’s default effort even if you previously set a different level for another model: `high` on Fable 5 and Opus 4.8, and `xhigh` on Opus 4.7. Run `/effort` again to choose a different level after switching. `low`, `medium`, `high`, and `xhigh` persist across sessions. `max` provides the deepest reasoning with no constraint on token spending and applies to the current session only, except when set through the `CLAUDE_CODE_EFFORT_LEVEL` environment variable. The `/effort` menu also offers `ultracode`. Ultracode is a Claude Code setting rather than a model effort level: it sends `xhigh` to the model and additionally has Claude orchestrate [dynamic workflows](</docs/en/workflows>) for substantive tasks. It applies to the current session only. Set it through `/effort`, or pass `"ultracode": true` via `--settings` or an Agent SDK control request. It is not part of the `effortLevel` setting, the `--effort` flag, or `CLAUDE_CODE_EFFORT_LEVEL`.
+If you set a level the active model does not support, Claude Code falls back to the highest supported level at or below the one you set. For example, `xhigh` runs as `high` on Opus 4.6. Your organization can also cap which levels are available for a model; see Organization effort limits. The default effort is `high` on Fable 5, Sonnet 5, Opus 4.8, Opus 4.6, and Sonnet 4.6, and `xhigh` on Opus 4.7. When you first run Fable 5, Opus 4.8, or Opus 4.7, Claude Code applies that model’s default effort even if you previously set a different level for another model: `high` on Fable 5 and Opus 4.8, and `xhigh` on Opus 4.7. Run `/effort` again to choose a different level after switching. `low`, `medium`, `high`, and `xhigh` persist across sessions. `max` provides the deepest reasoning with no constraint on token spending and applies to the current session only, except when set through the `CLAUDE_CODE_EFFORT_LEVEL` environment variable. The `/effort` menu also offers `ultracode`. Ultracode is a Claude Code setting rather than a model effort level: it sends `xhigh` to the model and additionally has Claude orchestrate [dynamic workflows](</docs/en/workflows>) for substantive tasks. It applies to the current session only. You can turn on ultracode through any of the following:
+
+ * **`/effort`** : run `/effort ultracode`, or select it from the menu
+ * **`--effort` flag**: launch with `claude --effort ultracode`, which starts the session at `xhigh` effort with ultracode on
+ * **`--settings` or an Agent SDK control request**: pass `"ultracode": true`. An [`applyFlagSettings()`](</docs/en/agent-sdk/typescript#applyflagsettings>) request also accepts `effortLevel: "ultracode"`
+
+Passing `ultracode` to the `--effort` flag or the Agent SDK `effortLevel` value requires Claude Code v2.1.203 or later. Before v2.1.203, `--effort ultracode` printed `Unknown --effort value 'ultracode'` and the session started at the default effort. The persisted `effortLevel` setting and the `CLAUDE_CODE_EFFORT_LEVEL` environment variable don’t accept `ultracode`. When ultracode isn’t available, for example when [workflows are turned off](</docs/en/workflows#turn-workflows-off>), `--effort ultracode` sets `xhigh` effort only.
####
Show diff (131 lines)
--- a/modifying-system-prompts.md
+++ b/modifying-system-prompts.md
@@ -88,6 +88,24 @@
// Now Claude has access to your project guidelines from CLAUDE.md
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ messages = []
+
+ async for message in query(
+ prompt="Add a new React component for user profiles",
+ options=ClaudeAgentOptions(
+ system_prompt={
+ "type": "preset",
+ "preset": "claude_code", # Use Claude Code's system prompt
+ },
+ setting_sources=["project"], # Loads CLAUDE.md from project
+ ),
+ ):
+ messages.append(message)
+
+ # Now Claude has access to your project guidelines from CLAUDE.md
+
CLAUDE.md is persistent across all sessions in a project, shared with your team through git, and discovered automatically without code changes. It is not loaded if you pass an empty `settingSources` array.
###
@@ -169,6 +187,24 @@
console.log(message.message.content);
}
}
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage
+
+ messages = []
+
+ async for message in query(
+ prompt="Help me write a Python function to calculate fibonacci numbers",
+ options=ClaudeAgentOptions(
+ system_prompt={
+ "type": "preset",
+ "preset": "claude_code",
+ "append": "Always include detailed docstrings and type hints in Python code.",
+ }
+ ),
+ ):
+ messages.append(message)
+ if isinstance(message, AssistantMessage):
+ print(message.content)
####
@@ -202,6 +238,21 @@
// ...
}
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async for message in query(
+ prompt="Triage the open issues in this repo",
+ options=ClaudeAgentOptions(
+ system_prompt={
+ "type": "preset",
+ "preset": "claude_code",
+ "append": "You operate Acme's internal triage workflow. Label issues by component and severity.",
+ "exclude_dynamic_sections": True,
+ },
+ ),
+ ):
+ ...
+
**Tradeoffs:** the working directory, the git-repo flag, the platform, the active shell, the OS version, and auto-memory paths still reach Claude, but as part of the first user message rather than the system prompt. Instructions in the user message carry marginally less weight than the same text in the system prompt, so Claude may rely on them less strongly when reasoning about the current directory or auto-memory paths. Enable this option when cross-session cache reuse matters more than maximally authoritative environment context. For the equivalent flag in non-interactive CLI mode, see [`--exclude-dynamic-system-prompt-sections`](</docs/en/cli-reference>).
###
@@ -239,6 +290,26 @@
console.log(message.message.content);
}
}
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage
+
+ custom_prompt = """You are a Python coding specialist.
+ Follow these guidelines:
+ - Write clean, well-documented code
+ - Use type hints for all functions
+ - Include comprehensive docstrings
+ - Prefer functional programming patterns when appropriate
+ - Always explain your code choices"""
+
+ messages = []
+
+ async for message in query(
+ prompt="Create a data processing pipeline",
+ options=ClaudeAgentOptions(system_prompt=custom_prompt),
+ ):
+ messages.append(message)
+ if isinstance(message, AssistantMessage):
+ print(message.content)
##
@@ -367,6 +438,29 @@
messages.push(message);
}
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ # Assuming "Code Reviewer" output style is active (via /config or settings)
+ # Add session-specific focus areas
+ messages = []
+
+ async for message in query(
+ prompt="Review this authentication module",
+ options=ClaudeAgentOptions(
+ system_prompt={
+ "type": "preset",
+ "preset": "claude_code",
+ "append": """
+ For this review, prioritize:
+ - OAuth 2.0 compliance
+ - Token storage security
+ - Session management
+ """,
+ }
+ ),
+ ):
+ messages.append(message)
+
##
--- a/observability.md
+++ b/observability.md
@@ -66,6 +66,31 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ const otelEnv = {
+ CLAUDE_CODE_ENABLE_TELEMETRY: "1",
+ // Required for traces, which are in beta. Metrics and log events do not need this.
+ CLAUDE_CODE_ENHANCED_TELEMETRY_BETA: "1",
+ // Choose an exporter per signal. Use otlp for the SDK; see the Note below.
+ OTEL_TRACES_EXPORTER: "otlp",
+ OTEL_METRICS_EXPORTER: "otlp",
+ OTEL_LOGS_EXPORTER: "otlp",
+ // Standard OTLP transport configuration.
+ OTEL_EXPORTER_OTLP_PROTOCOL: "http/protobuf",
+ OTEL_EXPORTER_OTLP_ENDPOINT: "http://collector.example.com:4318",
+ OTEL_EXPORTER_OTLP_HEADERS: "Authorization=Bearer your-token",
+ };
+
+ for await (const message of query({
+ prompt: "List the files in this directory",
+ // env replaces the inherited environment in TypeScript, so spread
+ // process.env first to keep PATH, ANTHROPIC_API_KEY, and other variables.
+ options: { env: { ...process.env, ...otelEnv } },
+ })) {
+ console.log(message);
+ }
+
Because the child process inherits your application’s environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely.
The `console` exporter writes telemetry to standard output, which the SDK uses as its message channel. Do not set `console` as an exporter value when running through the SDK. To inspect telemetry locally, point `OTEL_EXPORTER_OTLP_ENDPOINT` at a local collector or an all-in-one Jaeger container instead.
@@ -88,6 +113,13 @@
"OTEL_LOGS_EXPORT_INTERVAL": "1000",
"OTEL_TRACES_EXPORT_INTERVAL": "1000",
}
+
+ const otelEnv = {
+ // ... exporter configuration from the previous example ...
+ OTEL_METRIC_EXPORT_INTERVAL: "1000",
+ OTEL_LOGS_EXPORT_INTERVAL: "1000",
+ OTEL_TRACES_EXPORT_INTERVAL: "1000",
+ };
##
@@ -134,6 +166,16 @@
},
)
+ const options = {
+ env: {
+ ...process.env,
+ // ... exporter configuration ...
+ OTEL_SERVICE_NAME: "support-triage-agent",
+ OTEL_RESOURCE_ATTRIBUTES:
+ "service.version=1.4.0,deployment.environment=production",
+ },
+ };
+
##
@@ -155,6 +197,14 @@
},
)
+ const options = {
+ env: {
+ ...process.env,
+ // ... exporter configuration ...
+ OTEL_RESOURCE_ATTRIBUTES: `enduser.id=${encodeURIComponent(request.userId)},tenant.id=${encodeURIComponent(request.tenantId)}`,
+ },
+ };
+
With end-user identity attached, the `tool_decision`, `tool_result`, `mcp_server_connection`, and `permission_mode_changed` events, which export as log records named with a `claude_code.` prefix, become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
##
--- a/permission-modes.md
+++ b/permission-modes.md
@@ -37,7 +37,7 @@
* Web and mobile
-**During a session** : press `Shift+Tab` to cycle `default` → `acceptEdits` → `plan`. The current mode appears in the status bar. Not every mode is in the default cycle:
+**During a session** : press `Shift+Tab` to cycle `default` → `acceptEdits` → `plan`. The current mode appears in the status bar. Manual mode, `default` in that cycle, shows a gray `⏸ manual mode on` badge. Before v2.1.203, the status bar showed no badge in Manual mode.Not every mode is in the default cycle:
* `auto`: appears when your account meets the auto mode requirements; cycling to it switches modes without a confirmation prompt
* `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, or `--allow-dangerously-skip-permissions`; the `--allow-` variant adds the mode to the cycle without activating it
@@ -186,7 +186,8 @@
* Granting IAM or repo permissions
* Modifying shared infrastructure
* Irreversibly destroying files that existed before the session
- * Force push, or pushing directly to `main`
+ * Force push
+ * Pushing to the repository’s default branch when the push carries sensitive content such as secrets or personal or entrusted data, carries changes concealed or misdescribed relative to what you asked for, carries content ported in or first read from outside the repository, or routes around a pull request, review, or check you asked for. A plain push to the default branch isn’t blocked on its own, and clearing a flagged push requires naming the flagged content or the bypassed review, not only the push. The classifier is one layer: [`permissions.deny` rules](</docs/en/permissions#manage-permissions>) apply in every mode and can block pushes to the default branch outright, and the remote’s own branch protection still applies. Before v2.1.203, any direct push to the default branch was blocked
* `git reset --hard`, `git checkout -- .`, `git restore .`, `git clean -fd`, `git stash drop`, or `git stash clear`, which the classifier presumes would discard uncommitted changes
* `git commit --amend` when the commit at HEAD was not created in this session
* From v2.1.198, `git commit --amend` when the commit at HEAD has already been pushed. A message-only reword is not blocked: `--amend -m` with nothing newly staged, on a commit that Claude created during this session
@@ -213,7 +214,7 @@
Claude Code v2.1.198 and later also block these by default:
* Deleting files in `/tmp`, `$TMPDIR`, or another shared scratch or cache directory by wildcard, glob, or age filter rather than by a specific named path
- * Including sensitive details in content sent, uploaded, published, or written to other people or shared systems, when your own message didn’t authorize those details for that recipient. PR and issue bodies, commit messages, and comments count as this kind of outbound content when the repository is outside the trust boundary or public, including your organization’s own public repositories; internal file paths, code names, live API response data such as emails or account identifiers, and infrastructure identifiers count as sensitive details. The PR, issue, and commit-message scoping requires Claude Code v2.1.200 or later
+ * Including sensitive details in content sent, uploaded, published, or written to other people or shared systems, when your own message didn’t authorize those details for that recipient. PR and issue bodies, commit messages, and comments count as this kind of outbound content when the repository is outside the trust boundary or public, including your organization’s own public repositories; internal file paths, code names, live API response data such as emails or account identifiers, and infrastructure identifiers count as sensitive details. The PR, issue, and commit-message scoping requires Claude Code v2.1.200 or later. Live personal data from an API response in a PR or issue body, such as an email address, an account or organization identifier, or a usage metric, requires you to name those details and the recipient regardless of the repository’s visibility or trust boundary. That check requires Claude Code v2.1.203 or later
* Sending keystrokes to Claude Code’s own tmux pane to drive its own interface, which the classifier treats as Claude changing its own permissions or oversight
Claude Code v2.1.200 and later also block these by default:
@@ -222,8 +223,12 @@
* Deleting or tearing down a stateful resource Claude didn’t create in the session, when no more specific deletion rule applies and you didn’t name that resource
* Repointing an API base URL, proxy endpoint, webhook receiver, or registry mirror at a third-party host that doesn’t fit the task, including in example files like `.env.example`
* Changing where pushes go with `git remote set-url` or `git remote add`, unless you named the new remote
- * Pushing secrets to a repository known to be public, or pushing other sensitive or confidential material there that isn’t part of that repository’s own work. When a repository’s visibility isn’t established, the classifier doesn’t block on that alone; it judges the content against the other rules instead
+ * Pushing secrets or personal or entrusted data to a repository known to be public, or pushing confidential material there that isn’t part of that repository’s own work. A dotfiles repository’s own subject matter is the one exception for personal or entrusted data, and content from a private repository reaching any public surface is blocked the same way; both refinements require Claude Code v2.1.203 or later. Before v2.1.203, personal data was grouped with confidential material and blocked only when it wasn’t part of that repository’s own work. When a repository’s visibility isn’t established, the classifier doesn’t block on that alone; it judges the content against the other rules instead
* Opening a pull request against a different repository or organization, forking with `gh repo fork`, or pushing to a third-party repository, unless you named that external target
+
+Claude Code v2.1.203 and later also block these by default:
+
+ * Content from a sensitive local store, or from a file whose name, path, or type marks it as sensitive, entering a commit, a push, PR or issue text, a gist or paste, or a package publish, unless you named both the source and the destination. Session transcripts and conversation logs, credential and configuration dot-folders such as SSH keys, cloud credentials, browser profiles, and shell history, and user-data exports all count, and the repository being private doesn’t clear it
**Allowed by default** :
--- a/plugin-hints.md
+++ b/plugin-hints.md
@@ -41,6 +41,22 @@
'<claude-code-hint v="1" type="plugin" value="example-cli@claude-plugins-official" />\n',
)
}
+
+ import os, sys
+
+ if os.environ.get("CLAUDECODE"):
+ print(
+ '<claude-code-hint v="1" type="plugin" value="example-cli@claude-plugins-official" />',
+ file=sys.stderr,
+ )
+
+ if os.Getenv("CLAUDECODE") != "" {
+ fmt.Fprintln(os.Stderr,
+ `<claude-code-hint v="1" type="plugin" value="example-cli@claude-plugins-official" />`)
+ }
+
+ [ -n "$CLAUDECODE" ] &&
+ printf '%s\n' '<claude-code-hint v="1" type="plugin" value="example-cli@claude-plugins-official" />' >&2
Replace `example-cli` with your plugin’s name in the official marketplace.
--- a/plugins.md
+++ b/plugins.md
@@ -179,7 +179,7 @@
You’ve created a plugin with a skill, but plugins can include much more: custom agents, hooks, MCP servers, LSP servers, and background monitors.
-**Common mistake** : Don’t put `commands/`, `agents/`, `skills/`, or `hooks/` inside the `.claude-plugin/` directory. Only `plugin.json` goes inside `.claude-plugin/`. All other directories must be at the plugin root level.
+**Common mistake** : Don’t put `commands/`, `agents/`, `skills/`, or `hooks/` inside the `.claude-plugin/` directory. Only `plugin.json` goes inside `.claude-plugin/`. All other directories must be at the plugin root level.The plugin root is the individual plugin’s own directory: the one containing `.claude-plugin/plugin.json`. It is never `~/.claude/`. For example, Claude Code doesn’t read a `.mcp.json` placed at `~/.claude/.mcp.json`.
Directory| Location| Purpose
---|---|---
--- a/plugins-reference.md
+++ b/plugins-reference.md
@@ -603,7 +603,7 @@
Environment variables
-Claude Code provides three variables for referencing paths. All are substituted inline anywhere they appear in skill content, agent content, hook commands, monitor commands, and MCP or LSP server configs. All are also exported as environment variables to hook processes and MCP or LSP server subprocesses. **`${CLAUDE_PLUGIN_ROOT}`** : the absolute path to your plugin’s installation directory. Use this to reference scripts, binaries, and config files bundled with the plugin. In hook commands, use [exec form](</docs/en/hooks#exec-form-and-shell-form>) with `args` so the path is passed as one argument with no quoting. In shell-form hooks and monitor commands, wrap it in double quotes, as in `"${CLAUDE_PLUGIN_ROOT}"`. This path changes when the plugin updates. The previous version’s directory remains on disk for about seven days after an update before cleanup, but treat it as ephemeral and do not write state here. When a plugin updates mid-session, hook commands, monitors, MCP servers, and LSP servers keep using the previous version’s path. Run `/reload-plugins` to switch hooks, MCP servers, and LSP servers to the new path; monitors require a session restart. **`${CLAUDE_PLUGIN_DATA}`** : a persistent directory for plugin state that survives updates. Use this for installed dependencies such as `node_modules` or Python virtual environments, generated code, caches, and any other files that should persist across plugin versions. The directory is created automatically the first time this variable is referenced. **`${CLAUDE_PROJECT_DIR}`** : the project root. This is the same directory hooks receive in their `CLAUDE_PROJECT_DIR` variable. Use this to reference project-local scripts or config files. Wrap in quotes to handle paths with spaces, for example `"${CLAUDE_PROJECT_DIR}/scripts/server.sh"`. MCP servers can also call the MCP `roots/list` request, which returns the directory Claude Code was launched from.
+Claude Code provides three variables for referencing paths. All are substituted inline anywhere they appear in skill content, agent content, hook commands, monitor commands, and MCP or LSP server configs. All are also exported as environment variables to hook processes and MCP or LSP server subprocesses. **`${CLAUDE_PLUGIN_ROOT}`** : the absolute path to your plugin’s installation directory. Use this to reference scripts, binaries, and config files bundled with the plugin. In hook commands, use [exec form](</docs/en/hooks#exec-form-and-shell-form>) with `args` so the path is passed as one argument with no quoting. In shell-form hooks and monitor commands, wrap it in double quotes, as in `"${CLAUDE_PLUGIN_ROOT}"`. This path changes when the plugin updates. The previous version’s directory remains on disk for about seven days after an update before cleanup, but treat it as ephemeral and do not write state here. When a plugin updates mid-session, hook commands, monitors, MCP servers, and LSP servers keep using the previous version’s path. Run `/reload-plugins` to switch hooks, MCP servers, and LSP servers to the new path; monitors require a session restart. **`${CLAUDE_PLUGIN_DATA}`** : a persistent directory for plugin state that survives updates. Use this for installed dependencies such as `node_modules` or Python virtual environments, generated code, caches, and any other files that should persist across plugin versions. The directory is created automatically the first time this variable is referenced. **`${CLAUDE_PROJECT_DIR}`** : the project root. This is the same directory hooks receive in their `CLAUDE_PROJECT_DIR` variable. Use this to reference project-local scripts or config files. Wrap in quotes to handle paths with spaces, for example `"${CLAUDE_PROJECT_DIR}/scripts/server.sh"`. MCP servers can also call the `roots/list` request to read the session’s working directories at runtime. See [what `roots/list` returns and when Claude Code notifies the server of changes](</docs/en/mcp#option-3-add-a-local-stdio-server>).
{
"hooks": {
--- a/remote-control.md
+++ b/remote-control.md
@@ -125,7 +125,7 @@
Enable Remote Control for all sessions
-Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`, unless auto-connect is turned on. To enable it automatically for every interactive session, run `/config` inside Claude Code and set **Enable Remote Control for all sessions** to `true`. Set it to `false` to never auto-connect, or leave it unset to follow your organization’s default. In the Desktop app, you can also toggle this from **Settings → Claude Code → Enable remote control by default**. With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own environment and session. To run multiple concurrent sessions from a single process, use server mode instead.
+Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`, unless auto-connect is turned on. To enable it automatically for every interactive session, run `/config` inside Claude Code and set **Enable Remote Control for all sessions** to `true`. Set it to `false` to never auto-connect, or leave it unset to follow your organization’s default. In the Desktop app, you can also toggle this from **Settings → Claude Code → Enable remote control by default**. In the [VS Code extension](</docs/en/vs-code#use-the-prompt-box>), the same toggle appears as **Enable Remote Control for all sessions** in the command menu’s Settings section; requires Claude Code v2.1.203 or later. With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own environment and session. To run multiple concurrent sessions from a single process, use server mode instead.
##
--- a/security-guidance.md
+++ b/security-guidance.md
@@ -209,7 +209,7 @@
/plugin uninstall security-guidance@claude-plugins-official
-If the plugin was enabled through a project’s `.claude/settings.json`, disabling it from `/plugin` writes an override to your `.claude/settings.local.json` rather than editing the checked-in file, so the plugin stays off for you while teammates are unaffected. If it was enabled through [managed settings](</docs/en/admin-setup>), only an administrator can disable it.
+If the plugin was enabled through a project’s `.claude/settings.json`, disabling it from `/plugin` writes an override to your `.claude/settings.local.json` rather than editing the checked-in file, so the plugin stays off for you while teammates are unaffected. The same dialog also offers to uninstall the plugin for everyone by removing it from the shared `.claude/settings.json`; that option requires Claude Code v2.1.203 or later. If it was enabled through [managed settings](</docs/en/admin-setup>), only an administrator can disable it.
##
--- a/session-storage.md
+++ b/session-storage.md
@@ -41,6 +41,28 @@
}): Promise<string[]>;
};
+ # Exported from claude_agent_sdk as
+ # SessionStore, SessionKey, SessionStoreEntry.
+
+ class SessionKey(TypedDict):
+ project_key: str
+ session_id: str
+ subpath: NotRequired[str]
+
+ class SessionStore(Protocol):
+ # Required
+ async def append(
+ self, key: SessionKey, entries: list[SessionStoreEntry]
+ ) -> None: ...
+ async def load(self, key: SessionKey) -> list[SessionStoreEntry] | None: ...
+
+ # Optional — omit or raise NotImplementedError
+ async def list_sessions(
+ self, project_key: str
+ ) -> list[SessionStoreListEntry]: ...
+ async def delete(self, key: SessionKey) -> None: ...
+ async def list_subkeys(self, key: SessionListSubkeysKey) -> list[str]: ...
+
`SessionKey` addresses one transcript. `projectKey` is a stable, filesystem-safe encoding of the working directory, `sessionId` is the session UUID, and `subpath` is set when the entry belongs to a subagent transcript or sidecar file rather than the main conversation. Treat `subpath` as an opaque key suffix; it follows the on-disk layout, for example `subagents/agent-<id>`. When `subpath` is undefined the key refers to the main transcript.
Method| Required| Called when
@@ -86,6 +108,35 @@
console.log(message.result);
}
}
+
+ import asyncio
+ from claude_agent_sdk import (
+ ClaudeAgentOptions,
+ InMemorySessionStore,
+ ResultMessage,
+ query,
+ )
+
+ store = InMemorySessionStore()
+
+ async def main():
+ session_id = None
+ async for message in query(
+ prompt="List the Python files under src/",
+ options=ClaudeAgentOptions(session_store=store),
+ ):
+ if isinstance(message, ResultMessage):
+ session_id = message.session_id
+
+ # Resume from the store. The agent has full context from the first call.
+ async for message in query(
+ prompt="Summarize what those files do",
+ options=ClaudeAgentOptions(session_store=store, resume=session_id),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+
+ asyncio.run(main())
The second query prints a summary of the files from the first query, which shows the agent resumed with full context from the store.
--- a/settings.md
+++ b/settings.md
@@ -228,7 +228,7 @@
`channelsEnabled`| (Managed settings only) Allow [channels](</docs/en/channels>) for the organization. On claude.ai Team and Enterprise plans, channels are blocked when this is unset or `false`. For [Anthropic Console](</docs/en/authentication#claude-console-authentication>) accounts using API key authentication, channels are allowed by default unless your organization deploys managed settings, in which case this key must be set to `true`| `true`
`claudeMd`| (Managed settings only) CLAUDE.md-style instructions injected as organization-managed memory. Only honored when set in managed or policy settings and ignored in user, project, and local settings. See [organization-wide CLAUDE.md](</docs/en/memory#deploy-organization-wide-claude-md>)| `"Always run make lint before committing."`
`claudeMdExcludes`| Glob patterns or absolute paths of `CLAUDE.md` files to skip when loading [memory](</docs/en/memory>). Patterns match against absolute file paths. Only applies to user, project, and local memory; managed policy files cannot be excluded| `["**/vendor/**/CLAUDE.md"]`
-`cleanupPeriodDays`| **Default** : `30` days, minimum `1`. Session files older than this period are deleted at startup. Setting to `0` is rejected with a validation error. Also controls the age cutoff for automatic removal of [orphaned subagent worktrees](</docs/en/worktrees#clean-up-worktrees>) at startup. To disable transcript writes entirely, set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>) environment variable, or in non-interactive mode (`-p`) use the `--no-session-persistence` flag or the `persistSession: false` SDK option.| `20`
+`cleanupPeriodDays`| **Default** : `30` days, minimum `1`. Claude Code deletes [session files and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than this period at startup. Setting `0` fails with a validation error. The same age cutoff applies to automatic removal of [orphaned worktrees](</docs/en/worktrees#clean-up-worktrees>) at startup. If Claude Code can’t read or parse a settings file, it pauses the retention cleanup sweep and shows a warning in `/status` until you fix the file, unless [managed settings](</docs/en/server-managed-settings>) provide `cleanupPeriodDays`, in which case the sweep runs at the managed value. Before v2.1.203, cleanup ran at the 30-day default in that state and could delete transcripts a longer `cleanupPeriodDays` was meant to keep; files newer than 30 days were never removed. To disable transcript writes entirely, set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>) environment variable. In non-interactive mode, pass `--no-session-persistence` alongside `-p` or set `persistSession: false` in the Agent SDK.| `20`
`companyAnnouncements`| Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random.| `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]`
`defaultShell`| **Default** : `"bash"`, or `"powershell"` on Windows when Bash isn’t available. Default shell for input-box `!` commands. Accepts `"bash"` or `"powershell"`. Setting `"powershell"` routes interactive `!` commands through PowerShell on Windows. Requires `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. See [PowerShell tool](</docs/en/tools-reference#powershell-tool>)| `"powershell"`
`deniedMcpServers`| When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](</docs/en/managed-mcp>)| `[{ "serverName": "filesystem" }]`
@@ -305,7 +305,7 @@
`terminalProgressBarEnabled`| **Default** : `true`. Show the terminal progress bar in supported terminals: ConEmu, Ghostty 1.2.0+, and iTerm2 3.6.6+. Appears in `/config` as **Terminal progress bar**| `false`
`theme`| **Default** : `"dark"`. Color theme for the interface: `"auto"`, `"dark"`, `"light"`, `"dark-daltonized"`, `"light-daltonized"`, `"dark-ansi"`, `"light-ansi"`, or a custom theme reference such as `"custom:<slug>"` or `"custom:<plugin-name>:<slug>"`. See [Create a custom theme](</docs/en/terminal-config#create-a-custom-theme>). Appears in `/config` as **Theme**| `"dark"`
`tui`| Terminal UI renderer. Use `"fullscreen"` for the flicker-free [alt-screen renderer](</docs/en/fullscreen>) with virtualized scrollback. Use `"default"` for the classic main-screen renderer. Set via `/tui`. You can also set the [`CLAUDE_CODE_NO_FLICKER`](</docs/en/env-vars>) environment variable. Background sessions opened from [agent view](</docs/en/agent-view>) always use the fullscreen renderer regardless of this setting| `"fullscreen"`
-`ultracode`| Turn on [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>) for the session. Session-only and not read from `settings.json`. Set through `/effort ultracode`, `--settings`, or an Agent SDK control request| `true`
+`ultracode`| Turn on [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>) for the current session. This key isn’t read from `settings.json`. Set it through `/effort ultracode`, `--settings`, or an Agent SDK control request. To start a session with ultracode already on, launch with `claude --effort ultracode`, which requires Claude Code v2.1.203 or later| `true`
`useAutoModeDuringPlan`| **Default** : `true`. Whether plan mode uses auto mode semantics when auto mode is available. Not read from shared project settings. Appears in `/config` as “Use auto mode during plan”| `false`
`verbose`| **Default** : `false`. Show full tool output instead of truncated summaries. Appears in `/config` as **Verbose output**. The `--verbose` flag overrides this for one session| `true`
`viewMode`| Default transcript view mode on startup: `"default"`, `"verbose"`, or `"focus"`. Overrides the sticky `/focus` selection when set. The `--verbose` flag overrides this for one session| `"verbose"`
@@ -331,7 +331,7 @@
`autoInstallIdeExtension`| **Default** : `true`. Automatically install the Claude Code IDE extension when running from a VS Code terminal. 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`](</docs/en/env-vars>) environment variable to `1`| `false`
`externalEditorContext`| **Default** : `false`. Prepend Claude’s previous response as `#`-commented context when you open the external editor with `Ctrl+G`. Appears in `/config` as **Show last response in external editor**| `true`
`teammateDefaultModel`| Default model for [agent team](</docs/en/agent-teams>) teammates when the spawn prompt doesn’t 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**| `"sonnet"`
-`workflowSizeGuideline`| **Default** : `unrestricted`, which sends no guideline. Sets the [agent count Claude aims for](</docs/en/workflows#set-a-size-guideline>) in the dynamic workflows it writes. Claude Code sends the value to Claude as advice, not an enforced cap. Accepts `unrestricted`, `small`, `medium`, or `large`. Appears in `/config` as **Dynamic workflow size**. You can also set it directly with `/config workflowSizeGuideline=small`. Requires Claude Code v2.1.202 or later| `"small"`
+`workflowSizeGuideline`| **Default** : `unrestricted`, which sends no guideline. Sets the [agent count Claude aims for](</docs/en/workflows#set-a-size-guideline>) in the dynamic workflows it writes. Claude Code sends the value to Claude as advice, not an enforced cap. Accepts `unrestricted`, `small`, `medium`, or `large`. Appears in `/config` as **Dynamic workflow size**. You can also set it directly with `/config workflowSizeGuideline=small`. Requires Claude Code v2.1.202 or later. The guideline’s agent count also replaces the default threshold for the [`Large workflow` warning](</docs/en/workflows#cost>); that behavior requires Claude Code v2.1.203 or later| `"small"`
###
@@ -346,7 +346,7 @@
`worktree.baseRef`| Which ref new worktrees branch from. `"fresh"` (default) branches from `origin/<default-branch>` for a clean tree matching the remote. `"head"` branches from your current local `HEAD`, so unpushed commits and feature-branch state are present in the worktree. Applies to `--worktree`, the `EnterWorktree` tool, and subagent isolation| `"head"`
`worktree.symlinkDirectories`| Directories to symlink from the main repository into each worktree to avoid duplicating large directories on disk. No directories are symlinked by default| `["node_modules", ".cache"]`
`worktree.sparsePaths`| Directories to check out in each worktree via git sparse-checkout. Only the listed directories plus root-level files are written to disk, which is faster in large monorepos| `["packages/my-app", "shared/utils"]`
-`worktree.bgIsolation`| Isolation mode for [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>). `"worktree"` (default) blocks `Edit`/`Write` in the main checkout until `EnterWorktree` is called. `"none"` lets background jobs edit the working copy directly. Requires Claude Code v2.1.143 or later| `"none"`
+`worktree.bgIsolation`| Isolation mode for [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>). `"worktree"` (default) blocks `Edit`/`Write` in the main checkout until `EnterWorktree` is called. Outside a git repository, a [`WorktreeCreate` hook](</docs/en/worktrees#non-git-version-control>) that fails releases the block so the session can edit the working directory in place; requires Claude Code v2.1.203 or later. `"none"` lets background jobs edit the working copy directly. Requires Claude Code v2.1.143 or later| `"none"`
To copy gitignored files like `.env` into new worktrees, use a [`.worktreeinclude` file](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) in your project root instead of a setting.
--- a/skills.md
+++ b/skills.md
@@ -105,7 +105,7 @@
* Its description says which directory it applies to.
* Claude picks the variant that matches the files it is working on.
-Typing `/deploy` runs the project-root skill. Type the qualified name `/apps/web:deploy` to run the nested variant explicitly. A `<skill-name>` entry in the enterprise, personal, or project locations can be a symlink to a directory elsewhere on disk. Claude Code follows the symlink and reads `SKILL.md` from the target directory, and if the same target is reachable from more than one location, Claude Code loads the skill once. Plugin skills handle symlinks differently; see [Share files within a marketplace with symlinks](</docs/en/plugins-reference#share-files-within-a-marketplace-with-symlinks>).
+Typing `/deploy` runs the project-root skill. Type the qualified name `/apps/web:deploy` to run the nested variant explicitly. When you or Claude invoke the unqualified name, the project-root skill loads, and Claude Code appends a list of the directory-qualified variants to its content with an instruction to also invoke any variant whose directory holds the files Claude is working on. A nested skill therefore still applies to work in its directory when only the unqualified name is invoked. Requires Claude Code v2.1.203 or later. A `<skill-name>` entry in the enterprise, personal, or project locations can be a symlink to a directory elsewhere on disk. Claude Code follows the symlink and reads `SKILL.md` from the target directory, and if the same target is reachable from more than one location, Claude Code loads the skill once. Plugin skills handle symlinks differently; see [Share files within a marketplace with symlinks](</docs/en/plugins-reference#share-files-within-a-marketplace-with-symlinks>).
Add a `.claude-plugin/plugin.json` to a skill folder and it loads as a [plugin](</docs/en/plugins-reference#skills-directory-plugins>) named `<name>@skills-dir`, so it can bundle agents, hooks, and MCP servers. In a project’s `.claude/skills/`, this requires accepting the workspace trust dialog first.
Show diff (177 lines)
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -24,6 +24,18 @@
// ["clear", "compact", "context", "usage", "code-review", "verify", ...]
}
}
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage
+
+ async def main():
+ async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):
+ if isinstance(message, SystemMessage) and message.subtype == "init":
+ print("Available slash commands:", message.data["slash_commands"])
+ # Includes built-in commands plus bundled skills, for example:
+ # ["clear", "compact", "context", "usage", "code-review", "verify", ...]
+
+ asyncio.run(main())
##
@@ -65,6 +77,34 @@
// Example output: Command executed, result subtype: success
}
}
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ async def main():
+ # Build up conversation history first
+ try:
+ async for message in query(
+ prompt="What does the README in this directory cover?",
+ options=ClaudeAgentOptions(max_turns=2),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result,
+ # so the follow-up query below still runs.
+ print(f"Session ended with an error: {error}")
+
+ # Send a slash command as a follow-up to the same conversation
+ async for message in query(
+ prompt="/compact",
+ options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
+ ):
+ if isinstance(message, ResultMessage):
+ print("Command executed, result subtype:", message.subtype)
+ # Example output: Command executed, result subtype: success
+
+ asyncio.run(main())
A query can end with an error result, for example when the `maxTurns` / `max_turns` limit is reached before the work completes. The final result message then has `is_error: true` and an error subtype such as `error_max_turns` instead of `success`.After yielding that final result message, the SDK raises an error, because the CLI process exits with a non-zero code.Wrap the loop in a `try`/`catch` in TypeScript or `try`/`except` in Python if your command might hit the limit, as shown in [Single Message Input](</docs/en/agent-sdk/streaming-vs-single-mode#single-message-input>), or set `maxTurns` high enough for the work to complete. In Python, catch `Exception`: the SDK surfaces error results as a plain `Exception`.
@@ -120,6 +160,39 @@
}
}
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage, SystemMessage
+
+ async def main():
+ # Compaction needs existing history, so have a conversation first
+ try:
+ async for message in query(
+ prompt="Explain what this project does",
+ options=ClaudeAgentOptions(max_turns=2),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result,
+ # so the follow-up query below still runs.
+ print(f"Session ended with an error: {error}")
+
+ # Compact the same conversation
+ async for message in query(
+ prompt="/compact",
+ options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
+ ):
+ if isinstance(message, SystemMessage) and message.subtype == "compact_boundary":
+ print("Compaction completed")
+ print("Pre-compaction tokens:", message.data["compact_metadata"]["pre_tokens"])
+ print("Trigger:", message.data["compact_metadata"]["trigger"])
+ # Example output:
+ # Compaction completed
+ # Pre-compaction tokens: 1842
+ # Trigger: manual
+
+ asyncio.run(main())
+
A `compact_boundary` message only arrives when compaction ran. With nothing to summarize, `/compact` reports the reason instead of raising: the run still ends with a `success` result, no `compact_boundary` message is emitted, and the result text carries the message, for example `Not enough messages to compact.` after a single short exchange. A fresh one-shot `query()` call starts with empty context, so use this pattern in a session with prior turns, for example in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>) or when resuming a session.
###
@@ -240,6 +313,33 @@
}
}
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage
+
+ async def main():
+ # Use a custom command
+ try:
+ async for message in query(
+ prompt="/refactor src/auth/login.py", options=ClaudeAgentOptions(max_turns=3)
+ ):
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if hasattr(block, "text"):
+ print("Refactoring suggestions:", block.text)
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result,
+ # so the second query below still runs.
+ print(f"Session ended with an error: {error}")
+
+ # Custom commands appear in the slash_commands list
+ async for message in query(prompt="Hello", options=ClaudeAgentOptions(max_turns=1)):
+ if isinstance(message, SystemMessage) and message.subtype == "init":
+ print("Available commands:", message.data["slash_commands"])
+ # Includes built-in commands plus bundled skills and your custom commands, for example:
+ # ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]
+
+ asyncio.run(main())
+
###
@@ -281,6 +381,18 @@
}
}
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ async def main():
+ # Pass arguments to custom command
+ async for message in query(prompt="/fix-issue 123 high", options=ClaudeAgentOptions(max_turns=5)):
+ # Command will process with $0="123" and $1="high"
+ if isinstance(message, ResultMessage):
+ print("Issue fixed:", message.result)
+
+ asyncio.run(main())
+
####
@@ -430,6 +542,27 @@
// Handle test results
}
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async def main():
+ # Run code review
+ try:
+ async for message in query(prompt="/review-pr", options=ClaudeAgentOptions(max_turns=3)):
+ # Process review feedback
+ pass
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result,
+ # so the second query below still runs.
+ print(f"Session ended with an error: {error}")
+
+ # Run specific tests
+ async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)):
+ # Handle test results
+ pass
+
+ asyncio.run(main())
+
##
Show diff (420 lines)
--- a/statusline.md
+++ b/statusline.md
@@ -351,6 +351,38 @@
echo "[$MODEL] $BAR $PCT%"
+ #!/usr/bin/env python3
+ import json, sys
+
+ # json.load reads and parses stdin in one step
+ data = json.load(sys.stdin)
+ model = data['model']['display_name']
+ # "or 0" handles null values
+ pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)
+
+ # String multiplication builds the bar
+ filled = pct * 10 // 100
+ bar = '▓' * filled + '░' * (10 - filled)
+
+ print(f"[{model}] {bar} {pct}%")
+
+ #!/usr/bin/env node
+ // Node.js reads stdin asynchronously with events
+ let input = '';
+ process.stdin.on('data', chunk => input += chunk);
+ process.stdin.on('end', () => {
+ const data = JSON.parse(input);
+ const model = data.model.display_name;
+ // Optional chaining (?.) safely handles null fields
+ const pct = Math.floor(data.context_window?.used_percentage || 0);
+
+ // String.repeat() builds the bar
+ const filled = Math.floor(pct * 10 / 100);
+ const bar = '▓'.repeat(filled) + '░'.repeat(10 - filled);
+
+ console.log(`[${model}] ${bar} ${pct}%`);
+ });
+
###
@@ -391,6 +423,58 @@
echo "[$MODEL] 📁 ${DIR##*/}"
fi
+ #!/usr/bin/env python3
+ import json, sys, subprocess, os
+
+ data = json.load(sys.stdin)
+ model = data['model']['display_name']
+ directory = os.path.basename(data['workspace']['current_dir'])
+
+ GREEN, YELLOW, RESET = '\033[32m', '\033[33m', '\033[0m'
+
+ try:
+ subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)
+ branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()
+ staged_output = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()
+ modified_output = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()
+ staged = len(staged_output.split('\n')) if staged_output else 0
+ modified = len(modified_output.split('\n')) if modified_output else 0
+
+ git_status = f"{GREEN}+{staged}{RESET}" if staged else ""
+ git_status += f"{YELLOW}~{modified}{RESET}" if modified else ""
+
+ print(f"[{model}] 📁 {directory} | 🌿 {branch} {git_status}")
+ except:
+ print(f"[{model}] 📁 {directory}")
+
+ #!/usr/bin/env node
+ const { execSync } = require('child_process');
+ const path = require('path');
+
+ let input = '';
+ process.stdin.on('data', chunk => input += chunk);
+ process.stdin.on('end', () => {
+ const data = JSON.parse(input);
+ const model = data.model.display_name;
+ const dir = path.basename(data.workspace.current_dir);
+
+ const GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RESET = '\x1b[0m';
+
+ try {
+ execSync('git rev-parse --git-dir', { stdio: 'ignore' });
+ const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();
+ const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;
+ const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;
+
+ let gitStatus = staged ? `${GREEN}+${staged}${RESET}` : '';
+ gitStatus += modified ? `${YELLOW}~${modified}${RESET}` : '';
+
+ console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} ${gitStatus}`);
+ } catch {
+ console.log(`[${model}] 📁 ${dir}`);
+ }
+ });
+
###
@@ -418,6 +502,35 @@
SECS=$((DURATION_SEC % 60))
echo "[$MODEL] 💰 $COST_FMT | ⏱️ ${MINS}m ${SECS}s"
+
+ #!/usr/bin/env python3
+ import json, sys
+
+ data = json.load(sys.stdin)
+ model = data['model']['display_name']
+ cost = data.get('cost', {}).get('total_cost_usd', 0) or 0
+ duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0
+
+ duration_sec = duration_ms // 1000
+ mins, secs = duration_sec // 60, duration_sec % 60
+
+ print(f"[{model}] 💰 ${cost:.2f} | ⏱️ {mins}m {secs}s")
+
+ #!/usr/bin/env node
+ let input = '';
+ process.stdin.on('data', chunk => input += chunk);
+ process.stdin.on('end', () => {
+ const data = JSON.parse(input);
+ const model = data.model.display_name;
+ const cost = data.cost?.total_cost_usd || 0;
+ const durationMs = data.cost?.total_duration_ms || 0;
+
+ const durationSec = Math.floor(durationMs / 1000);
+ const mins = Math.floor(durationSec / 60);
+ const secs = durationSec % 60;
+
+ console.log(`[${model}] 💰 $${cost.toFixed(2)} | ⏱️ ${mins}m ${secs}s`);
+ });
###
@@ -463,6 +576,66 @@
echo -e "${CYAN}[$MODEL]${RESET} 📁 ${DIR##*/}$BRANCH"
COST_FMT=$(printf '$%.2f' "$COST")
echo -e "${BAR_COLOR}${BAR}${RESET} ${PCT}% | ${YELLOW}${COST_FMT}${RESET} | ⏱️ ${MINS}m ${SECS}s"
+
+ #!/usr/bin/env python3
+ import json, sys, subprocess, os
+
+ data = json.load(sys.stdin)
+ model = data['model']['display_name']
+ directory = os.path.basename(data['workspace']['current_dir'])
+ cost = data.get('cost', {}).get('total_cost_usd', 0) or 0
+ pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)
+ duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0
+
+ CYAN, GREEN, YELLOW, RED, RESET = '\033[36m', '\033[32m', '\033[33m', '\033[31m', '\033[0m'
+
+ bar_color = RED if pct >= 90 else YELLOW if pct >= 70 else GREEN
+ filled = pct // 10
+ bar = '█' * filled + '░' * (10 - filled)
+
+ mins, secs = duration_ms // 60000, (duration_ms % 60000) // 1000
+
+ try:
+ branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True, stderr=subprocess.DEVNULL).strip()
+ branch = f" | 🌿 {branch}" if branch else ""
+ except:
+ branch = ""
+
+ print(f"{CYAN}[{model}]{RESET} 📁 {directory}{branch}")
+ print(f"{bar_color}{bar}{RESET} {pct}% | {YELLOW}${cost:.2f}{RESET} | ⏱️ {mins}m {secs}s")
+
+ #!/usr/bin/env node
+ const { execSync } = require('child_process');
+ const path = require('path');
+
+ let input = '';
+ process.stdin.on('data', chunk => input += chunk);
+ process.stdin.on('end', () => {
+ const data = JSON.parse(input);
+ const model = data.model.display_name;
+ const dir = path.basename(data.workspace.current_dir);
+ const cost = data.cost?.total_cost_usd || 0;
+ const pct = Math.floor(data.context_window?.used_percentage || 0);
+ const durationMs = data.cost?.total_duration_ms || 0;
+
+ const CYAN = '\x1b[36m', GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RED = '\x1b[31m', RESET = '\x1b[0m';
+
+ const barColor = pct >= 90 ? RED : pct >= 70 ? YELLOW : GREEN;
+ const filled = Math.floor(pct / 10);
+ const bar = '█'.repeat(filled) + '░'.repeat(10 - filled);
+
+ const mins = Math.floor(durationMs / 60000);
+ const secs = Math.floor((durationMs % 60000) / 1000);
+
+ let branch = '';
+ try {
+ branch = execSync('git branch --show-current', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
+ branch = branch ? ` | 🌿 ${branch}` : '';
+ } catch {}
+
+ console.log(`${CYAN}[${model}]${RESET} 📁 ${dir}${branch}`);
+ console.log(`${barColor}${bar}${RESET} ${pct}% | ${YELLOW}$${cost.toFixed(2)}${RESET} | ⏱️ ${mins}m ${secs}s`);
+ });
###
@@ -497,6 +670,51 @@
echo "[$MODEL]"
fi
+ #!/usr/bin/env python3
+ import json, sys, subprocess, re, os
+
+ data = json.load(sys.stdin)
+ model = data['model']['display_name']
+
+ # Get git remote URL
+ try:
+ remote = subprocess.check_output(
+ ['git', 'remote', 'get-url', 'origin'],
+ stderr=subprocess.DEVNULL, text=True
+ ).strip()
+ # Convert SSH to HTTPS format
+ remote = re.sub(r'^git@github\.com:', 'https://github.com/', remote)
+ remote = re.sub(r'\.git$', '', remote)
+ repo_name = os.path.basename(remote)
+ # OSC 8 escape sequences
+ link = f"\033]8;;{remote}\a{repo_name}\033]8;;\a"
+ print(f"[{model}] 🔗 {link}")
+ except:
+ print(f"[{model}]")
+
+ #!/usr/bin/env node
+ const { execSync } = require('child_process');
+ const path = require('path');
+
+ let input = '';
+ process.stdin.on('data', chunk => input += chunk);
+ process.stdin.on('end', () => {
+ const data = JSON.parse(input);
+ const model = data.model.display_name;
+
+ try {
+ let remote = execSync('git remote get-url origin', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
+ // Convert SSH to HTTPS format
+ remote = remote.replace(/^git@github\.com:/, 'https://github.com/').replace(/\.git$/, '');
+ const repoName = path.basename(remote);
+ // OSC 8 escape sequences
+ const link = `\x1b]8;;${remote}\x07${repoName}\x1b]8;;\x07`;
+ console.log(`[${model}] 🔗 ${link}`);
+ } catch {
+ console.log(`[${model}]`);
+ }
+ });
+
###
@@ -524,6 +742,44 @@
[ -n "$WEEK" ] && LIMITS="${LIMITS:+$LIMITS }7d: $(printf '%.0f' "$WEEK")%"
[ -n "$LIMITS" ] && echo "[$MODEL] | $LIMITS" || echo "[$MODEL]"
+
+ #!/usr/bin/env python3
+ import json, sys
+
+ data = json.load(sys.stdin)
+ model = data['model']['display_name']
+
+ parts = []
+ rate = data.get('rate_limits', {})
+ five_h = rate.get('five_hour', {}).get('used_percentage')
+ week = rate.get('seven_day', {}).get('used_percentage')
+
+ if five_h is not None:
+ parts.append(f"5h: {five_h:.0f}%")
+ if week is not None:
+ parts.append(f"7d: {week:.0f}%")
+
+ if parts:
+ print(f"[{model}] | {' '.join(parts)}")
+ else:
+ print(f"[{model}]")
+
+ #!/usr/bin/env node
+ let input = '';
+ process.stdin.on('data', chunk => input += chunk);
+ process.stdin.on('end', () => {
+ const data = JSON.parse(input);
+ const model = data.model.display_name;
+
+ const parts = [];
+ const fiveH = data.rate_limits?.five_hour?.used_percentage;
+ const week = data.rate_limits?.seven_day?.used_percentage;
+
+ if (fiveH != null) parts.push(`5h: ${Math.round(fiveH)}%`);
+ if (week != null) parts.push(`7d: ${Math.round(week)}%`);
+
+ console.log(parts.length ? `[${model}] | ${parts.join(' ')}` : `[${model}]`);
+ });
###
@@ -574,6 +830,86 @@
echo "[$MODEL] 📁 ${DIR##*/}"
fi
+ #!/usr/bin/env python3
+ import json, sys, subprocess, os, time
+
+ data = json.load(sys.stdin)
+ model = data['model']['display_name']
+ directory = os.path.basename(data['workspace']['current_dir'])
+ session_id = data['session_id']
+
+ CACHE_FILE = f"/tmp/statusline-git-cache-{session_id}"
+ CACHE_MAX_AGE = 5 # seconds
+
+ def cache_is_stale():
+ if not os.path.exists(CACHE_FILE):
+ return True
+ return time.time() - os.path.getmtime(CACHE_FILE) > CACHE_MAX_AGE
+
+ if cache_is_stale():
+ try:
+ subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)
+ branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()
+ staged = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()
+ modified = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()
+ staged_count = len(staged.split('\n')) if staged else 0
+ modified_count = len(modified.split('\n')) if modified else 0
+ with open(CACHE_FILE, 'w') as f:
+ f.write(f"{branch}|{staged_count}|{modified_count}")
+ except:
+ with open(CACHE_FILE, 'w') as f:
+ f.write("||")
+
+ with open(CACHE_FILE) as f:
+ branch, staged, modified = f.read().strip().split('|')
+
+ if branch:
+ print(f"[{model}] 📁 {directory} | 🌿 {branch} +{staged} ~{modified}")
+ else:
+ print(f"[{model}] 📁 {directory}")
+
+ #!/usr/bin/env node
+ const { execSync } = require('child_process');
+ const fs = require('fs');
+ const path = require('path');
+
+ let input = '';
+ process.stdin.on('data', chunk => input += chunk);
+ process.stdin.on('end', () => {
+ const data = JSON.parse(input);
+ const model = data.model.display_name;
+ const dir = path.basename(data.workspace.current_dir);
+ const sessionId = data.session_id;
+
+ const CACHE_FILE = `/tmp/statusline-git-cache-${sessionId}`;
+ const CACHE_MAX_AGE = 5; // seconds
+
+ const cacheIsStale = () => {
+ if (!fs.existsSync(CACHE_FILE)) return true;
+ return (Date.now() / 1000) - fs.statSync(CACHE_FILE).mtimeMs / 1000 > CACHE_MAX_AGE;
+ };
+
+ if (cacheIsStale()) {
+ try {
+ execSync('git rev-parse --git-dir', { stdio: 'ignore' });
+ const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();
+ const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;
+ const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;
+ fs.writeFileSync(CACHE_FILE, `${branch}|${staged}|${modified}`);
+ } catch {
+ fs.writeFileSync(CACHE_FILE, '||');
+ }
+ }
+
+ const [branch, staged, modified] = fs.readFileSync(CACHE_FILE, 'utf8').trim().split('|');
+
+ if (branch) {
+ console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} +${staged} ~${modified}`);
+ } else {
+ console.log(`[${model}] 📁 ${dir}`);
+ }
+ });
+
###
@@ -593,6 +929,18 @@
}
}
+ $input_json = $input | Out-String | ConvertFrom-Json
+ $cwd = $input_json.cwd
+ $model = $input_json.model.display_name
+ $used = $input_json.context_window.used_percentage
+ $dirname = Split-Path $cwd -Leaf
+
+ if ($used) {
+ Write-Host "$dirname [$model] ctx: $used%"
+ } else {
+ Write-Host "$dirname [$model]"
+ }
+
Or, when Git Bash is installed, run a Bash script directly:
settings.json
@@ -605,6 +953,13 @@
"command": "~/.claude/statusline.sh"
}
}
+
+ #!/usr/bin/env bash
+ input=$(cat)
+ cwd=$(echo "$input" | grep -o '"cwd":"[^"]*"' | cut -d'"' -f4)
+ model=$(echo "$input" | grep -o '"display_name":"[^"]*"' | cut -d'"' -f4)
+ dirname="${cwd##*[/\\]}"
+ echo "$dirname [$model]"
##
Show diff (160 lines)
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -40,6 +40,25 @@
asyncio.run(stream_response())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "List the files in my project",
+ options: {
+ includePartialMessages: true,
+ allowedTools: ["Bash", "Read"]
+ }
+ })) {
+ if (message.type === "stream_event") {
+ const event = message.event;
+ if (event.type === "content_block_delta") {
+ if (event.delta.type === "text_delta") {
+ process.stdout.write(event.delta.text);
+ }
+ }
+ }
+ }
+
##
@@ -63,6 +82,15 @@
session_id: str # Session identifier
event: dict[str, Any] # The raw Claude API stream event
parent_tool_use_id: str | None # Always None
+
+ type SDKPartialAssistantMessage = {
+ type: "stream_event";
+ event: BetaRawMessageStreamEvent; // From Anthropic SDK
+ parent_tool_use_id: string | null;
+ uuid: UUID;
+ session_id: string;
+ ttft_ms?: number; // Time to first token in ms, present only on message_start events
+ };
The `parent_tool_use_id` field is always `None` in Python and `null` in TypeScript. Stream events are emitted for the main session only; token-level deltas from subagents aren’t forwarded. To attribute output to a subagent, use complete messages, which carry `parent_tool_use_id`. See [Detect subagent invocation](</docs/en/agent-sdk/subagents#detect-subagent-invocation>). The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
@@ -131,6 +159,22 @@
asyncio.run(stream_text())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Explain how databases work",
+ options: { includePartialMessages: true }
+ })) {
+ if (message.type === "stream_event") {
+ const event = message.event;
+ if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
+ process.stdout.write(event.delta.text);
+ }
+ }
+ }
+
+ console.log(); // Final newline
+
##
@@ -190,6 +234,46 @@
asyncio.run(stream_tool_calls())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Track the current tool and accumulate its input JSON
+ let currentTool: string | null = null;
+ let toolInput = "";
+
+ for await (const message of query({
+ prompt: "Read the README.md file",
+ options: {
+ includePartialMessages: true,
+ allowedTools: ["Read", "Bash"]
+ }
+ })) {
+ if (message.type === "stream_event") {
+ const event = message.event;
+
+ if (event.type === "content_block_start") {
+ // New tool call is starting
+ if (event.content_block.type === "tool_use") {
+ currentTool = event.content_block.name;
+ toolInput = "";
+ console.log(`Starting tool: ${currentTool}`);
+ }
+ } else if (event.type === "content_block_delta") {
+ if (event.delta.type === "input_json_delta") {
+ // Accumulate JSON input as it streams in
+ const chunk = event.delta.partial_json;
+ toolInput += chunk;
+ console.log(` Input chunk: ${chunk}`);
+ }
+ } else if (event.type === "content_block_stop") {
+ // Tool call complete - show final input
+ if (currentTool) {
+ console.log(`Tool ${currentTool} called with: ${toolInput}`);
+ currentTool = null;
+ }
+ }
+ }
+ }
+
##
@@ -250,6 +334,45 @@
asyncio.run(streaming_ui())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Track whether we're currently in a tool call
+ let inTool = false;
+
+ for await (const message of query({
+ prompt: "Find all TODO comments in the codebase",
+ options: {
+ includePartialMessages: true,
+ allowedTools: ["Read", "Bash", "Grep"]
+ }
+ })) {
+ if (message.type === "stream_event") {
+ const event = message.event;
+
+ if (event.type === "content_block_start") {
+ if (event.content_block.type === "tool_use") {
+ // Tool call is starting - show status indicator
+ process.stdout.write(`\n[Using ${event.content_block.name}...]`);
+ inTool = true;
+ }
+ } else if (event.type === "content_block_delta") {
+ // Only stream text when not executing a tool
+ if (event.delta.type === "text_delta" && !inTool) {
+ process.stdout.write(event.delta.text);
+ }
+ } else if (event.type === "content_block_stop") {
+ if (inTool) {
+ // Tool call finished
+ console.log(" done");
+ inTool = false;
+ }
+ }
+ } else if (message.type === "result") {
+ // Agent finished all work
+ console.log("\n\n--- Complete ---");
+ }
+ }
+
##
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -115,6 +115,67 @@
}
}
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ AssistantMessage,
+ TextBlock,
+ )
+ import asyncio
+ import base64
+
+ async def streaming_analysis():
+ async def message_generator():
+ # First message
+ yield {
+ "type": "user",
+ "message": {
+ "role": "user",
+ "content": "Analyze this codebase for security issues",
+ },
+ }
+
+ # Wait for conditions
+ await asyncio.sleep(2)
+
+ # Follow-up with image
+ with open("diagram.png", "rb") as f:
+ image_data = base64.b64encode(f.read()).decode()
+
+ yield {
+ "type": "user",
+ "message": {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Review this architecture diagram"},
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": image_data,
+ },
+ },
+ ],
+ },
+ }
+
+ # Use ClaudeSDKClient for streaming input
+ options = ClaudeAgentOptions(max_turns=10, allowed_tools=["Read", "Grep"])
+
+ async with ClaudeSDKClient(options) as client:
+ # Send streaming input
+ await client.query(message_generator())
+
+ # Process responses
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(block.text)
+
+ asyncio.run(streaming_analysis())
+
In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator.
##
@@ -189,3 +250,25 @@
console.log(message.result);
}
}
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+ import asyncio
+
+ async def single_message_example():
+ # Simple one-shot query using query() function
+ async for message in query(
+ prompt="Explain the authentication flow",
+ options=ClaudeAgentOptions(max_turns=1, allowed_tools=["Read", "Grep"]),
+ ):
+ if isinstance(message, ResultMessage):
+ print(message.result)
+
+ # Continue conversation with session management
+ async for message in query(
+ prompt="Now explain the authorization process",
+ options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
+ ):
+ if isinstance(message, ResultMessage):
+ print(message.result)
+
+ asyncio.run(single_message_example())
Show diff (153 lines)
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -78,6 +78,34 @@
// { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }
}
}
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ # Define the shape of data you want back
+ schema = {
+ "type": "object",
+ "properties": {
+ "company_name": {"type": "string"},
+ "founded_year": {"type": "number"},
+ "headquarters": {"type": "string"},
+ },
+ "required": ["company_name"],
+ }
+
+ async def main():
+ async for message in query(
+ prompt="Research Anthropic and provide key company information",
+ options=ClaudeAgentOptions(
+ output_format={"type": "json_schema", "schema": schema}
+ ),
+ ):
+ # The result message contains structured_output with validated data
+ if isinstance(message, ResultMessage) and message.structured_output:
+ print(message.structured_output)
+ # {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}
+
+ asyncio.run(main())
##
@@ -137,6 +165,43 @@
}
}
}
+
+ import asyncio
+ from pydantic import BaseModel
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ class Step(BaseModel):
+ step_number: int
+ description: str
+ estimated_complexity: str # 'low', 'medium', 'high'
+
+ class FeaturePlan(BaseModel):
+ feature_name: str
+ summary: str
+ steps: list[Step]
+ risks: list[str]
+
+ async def main():
+ async for message in query(
+ prompt="Plan how to add dark mode support to a React app. Break it into implementation steps.",
+ options=ClaudeAgentOptions(
+ output_format={
+ "type": "json_schema",
+ "schema": FeaturePlan.model_json_schema(),
+ }
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.structured_output:
+ # Validate and get fully typed result
+ plan = FeaturePlan.model_validate(message.structured_output)
+ print(f"Feature: {plan.feature_name}")
+ print(f"Summary: {plan.summary}")
+ for step in plan.steps:
+ print(
+ f"{step.step_number}. [{step.estimated_complexity}] {step.description}"
+ )
+
+ asyncio.run(main())
**Benefits:**
@@ -217,6 +282,50 @@
}
}
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ # Define structure for TODO extraction
+ todo_schema = {
+ "type": "object",
+ "properties": {
+ "todos": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "text": {"type": "string"},
+ "file": {"type": "string"},
+ "line": {"type": "number"},
+ "author": {"type": "string"},
+ "date": {"type": "string"},
+ },
+ "required": ["text", "file", "line"],
+ },
+ },
+ "total_count": {"type": "number"},
+ },
+ "required": ["todos", "total_count"],
+ }
+
+ async def main():
+ # Agent uses Grep to find TODOs, Bash to get git blame info
+ async for message in query(
+ prompt="Find all TODO comments in this codebase and identify who added them",
+ options=ClaudeAgentOptions(
+ output_format={"type": "json_schema", "schema": todo_schema}
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.structured_output:
+ data = message.structured_output
+ print(f"Found {data['total_count']} TODOs")
+ for todo in data["todos"]:
+ print(f"{todo['file']}:{todo['line']} - {todo['text']}")
+ if "author" in todo:
+ print(f" Added by {todo['author']} on {todo['date']}")
+
+ asyncio.run(main())
+
##
@@ -256,6 +365,20 @@
}
}
+ async for message in query(
+ prompt="Extract contact info from the document",
+ options=ClaudeAgentOptions(
+ output_format={"type": "json_schema", "schema": contact_schema}
+ ),
+ ):
+ if isinstance(message, ResultMessage):
+ if message.subtype == "success" and message.structured_output:
+ # Use the validated output
+ print(message.structured_output)
+ elif message.subtype == "error_max_structured_output_retries":
+ # Handle the failure
+ print("Could not produce valid output")
+
**Tips for avoiding errors:**
* **Keep schemas focused.** Deeply nested schemas with many required fields are harder to satisfy. Start simple and add complexity as needed.
--- a/sub-agents.md
+++ b/sub-agents.md
@@ -208,7 +208,7 @@
You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.
-The frontmatter defines the subagent’s metadata and configuration. The body becomes the system prompt that guides the subagent’s behavior. Subagents receive only this system prompt plus basic environment details like the working directory, not the full Claude Code system prompt. A subagent starts in the main conversation’s current working directory. Within a subagent, `cd` commands don’t persist between Bash or PowerShell tool calls and don’t affect the main conversation’s working directory. To give the subagent an isolated copy of the repository instead, set `isolation: worktree`.
+The frontmatter defines the subagent’s metadata and configuration. The body becomes the system prompt that guides the subagent’s behavior. Subagents receive only this system prompt plus basic environment details like the working directory, not the full Claude Code system prompt. A subagent starts in the main conversation’s current working directory. Within a subagent, `cd` commands don’t persist between Bash or PowerShell tool calls and don’t affect the main conversation’s working directory. To give the subagent an isolated copy of the repository instead, set `isolation: worktree`. A subagent with `isolation: worktree` runs its Bash and PowerShell commands inside its worktree. A command whose working directory resolves to your main checkout instead, for example because the worktree directory was removed while the subagent was running, fails with an error. Before v2.1.203, such a command could run in the main checkout.
####
Show diff (221 lines)
--- a/subagents.md
+++ b/subagents.md
@@ -117,6 +117,52 @@
print(message.result)
asyncio.run(main())
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Review the authentication module for security issues",
+ options: {
+ // Auto-approve these tools, including Agent for subagent invocation
+ allowedTools: ["Read", "Grep", "Glob", "Agent"],
+ agents: {
+ "code-reviewer": {
+ // description tells Claude when to use this subagent
+ description:
+ "Expert code review specialist. Use for quality, security, and maintainability reviews.",
+ // prompt defines the subagent's behavior and expertise
+ prompt: `You are a code review specialist with expertise in security, performance, and best practices.
+
+ When reviewing code:
+ - Identify security vulnerabilities
+ - Check for performance issues
+ - Verify adherence to coding standards
+ - Suggest specific improvements
+
+ Be thorough but concise in your feedback.`,
+ // tools restricts what the subagent can do (read-only here)
+ tools: ["Read", "Grep", "Glob"],
+ // model overrides the default model for this subagent
+ model: "sonnet"
+ },
+ "test-runner": {
+ description:
+ "Runs and analyzes test suites. Use for test execution and coverage analysis.",
+ prompt: `You are a test execution specialist. Run tests and provide clear analysis of results.
+
+ Focus on:
+ - Running test commands
+ - Analyzing test output
+ - Identifying failing tests
+ - Suggesting fixes for failures`,
+ // Bash access lets this subagent run test commands
+ tools: ["Bash", "Read", "Grep"]
+ }
+ }
+ }
+ })) {
+ if ("result" in message) console.log(message.result);
+ }
###
@@ -245,6 +291,36 @@
print(message.result)
asyncio.run(main())
+
+ import { query, type AgentDefinition } from "@anthropic-ai/claude-agent-sdk";
+
+ // Factory function that returns an AgentDefinition
+ // This pattern lets you customize agents based on runtime conditions
+ function createSecurityAgent(securityLevel: "basic" | "strict"): AgentDefinition {
+ const isStrict = securityLevel === "strict";
+ return {
+ description: "Security code reviewer",
+ // Customize the prompt based on strictness level
+ prompt: `You are a ${isStrict ? "strict" : "balanced"} security reviewer...`,
+ tools: ["Read", "Grep", "Glob"],
+ // Key insight: use a more capable model for high-stakes reviews
+ model: isStrict ? "opus" : "sonnet"
+ };
+ }
+
+ // The agent is created at query time, so each request can use different settings
+ for await (const message of query({
+ prompt: "Review this PR for security issues",
+ options: {
+ allowedTools: ["Read", "Grep", "Glob", "Agent"],
+ agents: {
+ // Call the factory with your desired configuration
+ "security-reviewer": createSecurityAgent("strict")
+ }
+ }
+ })) {
+ if ("result" in message) console.log(message.result);
+ }
##
@@ -298,6 +374,41 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Use the code-reviewer agent to review this codebase",
+ options: {
+ allowedTools: ["Read", "Glob", "Grep", "Agent"],
+ agents: {
+ "code-reviewer": {
+ description: "Expert code reviewer.",
+ prompt: "Analyze code quality and suggest improvements.",
+ tools: ["Read", "Glob", "Grep"]
+ }
+ }
+ }
+ })) {
+ const msg = message as any;
+
+ // Check for subagent invocation. Match both names: older SDK versions
+ // emitted "Task", current versions emit "Agent".
+ for (const block of msg.message?.content ?? []) {
+ if (block.type === "tool_use" && (block.name === "Task" || block.name === "Agent")) {
+ console.log(`Subagent invoked: ${block.input.subagent_type}`);
+ }
+ }
+
+ // Check if this message is from within a subagent's context
+ if (msg.parent_tool_use_id) {
+ console.log(" (running inside subagent)");
+ }
+
+ if ("result" in message) {
+ console.log(message.result);
+ }
+ }
+
##
@@ -378,6 +489,59 @@
asyncio.run(main())
+ import { query, type SDKMessage } from "@anthropic-ai/claude-agent-sdk";
+
+ const agents = {
+ "endpoint-finder": {
+ description: "Locates and catalogs API endpoints in a codebase.",
+ prompt: "You find and document API endpoints. Report each endpoint's path, method, and handler.",
+ tools: ["Read", "Grep", "Glob"]
+ }
+ };
+
+ // Stringify content to search for agentId without traversing nested block types
+ function extractAgentId(message: SDKMessage): string | undefined {
+ if (message.type !== "assistant" && message.type !== "user") return undefined;
+ const content = JSON.stringify(message.message.content);
+ const match = content.match(/agentId:\s*([\w-]+)/);
+ return match?.[1];
+ }
+
+ let agentId: string | undefined;
+ let sessionId: string | undefined;
+
+ // First invocation - run the endpoint-finder subagent
+ try {
+ for await (const message of query({
+ prompt: "Use the endpoint-finder agent to find all API endpoints in this codebase",
+ options: { allowedTools: ["Read", "Grep", "Glob", "Agent"], agents }
+ })) {
+ // Capture session_id from ResultMessage (needed to resume this session)
+ if ("session_id" in message) sessionId = message.session_id;
+ // Search message content for the agentId (appears in Agent tool results)
+ const extractedId = extractAgentId(message);
+ if (extractedId) agentId = extractedId;
+ // Print the final result
+ if ("result" in message) console.log(message.result);
+ }
+ } catch (error) {
+ // A single-shot query() throws after yielding an error result,
+ // so sessionId and agentId have already been captured by the loop above.
+ console.error(`Session ended with an error: ${error}`);
+ }
+
+ // Second invocation - resume and ask follow-up
+ if (agentId && sessionId) {
+ for await (const message of query({
+ prompt: `Resume agent ${agentId} and list the top 3 most complex endpoints`,
+ options: { allowedTools: ["Read", "Grep", "Glob", "Agent"], agents, resume: sessionId }
+ })) {
+ if ("result" in message) console.log(message.result);
+ }
+ } else {
+ console.log("No agentId found in the first query, so there is no subagent to resume.");
+ }
+
Subagent transcripts persist independently of the main conversation:
* **Main conversation compaction** : when the main conversation compacts, subagent transcripts are unaffected. They’re stored in separate files.
@@ -425,6 +589,26 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Analyze the architecture of this codebase",
+ options: {
+ allowedTools: ["Read", "Grep", "Glob", "Agent"],
+ agents: {
+ "code-analyzer": {
+ description: "Static code analysis and architecture review",
+ prompt: `You are a code architecture analyst. Analyze code structure,
+ identify patterns, and suggest improvements without making changes.`,
+ // Read-only tools: no Edit, Write, or Bash access
+ tools: ["Read", "Grep", "Glob"]
+ }
+ }
+ }
+ })) {
+ if ("result" in message) console.log(message.result);
+ }
+
###
--- a/terminal-config.md
+++ b/terminal-config.md
@@ -296,6 +296,14 @@
CLAUDE_CODE_NO_FLICKER=1 claude
+ $env:CLAUDE_CODE_NO_FLICKER = "1"; claude
+
+ {
+ "env": {
+ "CLAUDE_CODE_NO_FLICKER": "1"
+ }
+ }
+
##
Show diff (148 lines)
--- a/todo-tracking.md
+++ b/todo-tracking.md
@@ -78,6 +78,41 @@
// such as when the maxTurns limit is hit.
console.log(`Session ended with an error: ${error}`);
}
+
+ import asyncio
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock
+
+ async def main():
+ try:
+ async for message in query(
+ prompt="Optimize my React app performance and track progress with todos",
+ # Re-enable TodoWrite, which this example monitors. Without it, the SDK uses
+ # Task tools instead and these tool_use blocks never appear.
+ options=ClaudeAgentOptions(max_turns=15, env={"CLAUDE_CODE_ENABLE_TASKS": "0"}),
+ ):
+ # Todo updates are reflected in the message stream
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, ToolUseBlock) and block.name == "TodoWrite":
+ todos = block.input["todos"]
+
+ print("Todo Status Update:")
+ for i, todo in enumerate(todos):
+ status = (
+ "✅"
+ if todo["status"] == "completed"
+ else "🔧"
+ if todo["status"] == "in_progress"
+ else "❌"
+ )
+ print(f"{i + 1}. {status} {todo['content']}")
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result,
+ # such as when the max_turns limit is hit.
+ print(f"Session ended with an error: {error}")
+
+ asyncio.run(main())
###
@@ -139,6 +174,65 @@
// Usage
const tracker = new TodoTracker();
await tracker.trackQuery("Build a complete authentication system with todos");
+
+ import asyncio
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock
+ from typing import List, Dict
+
+ class TodoTracker:
+ def __init__(self):
+ self.todos: List[Dict] = []
+
+ def display_progress(self):
+ if not self.todos:
+ return
+
+ completed = len([t for t in self.todos if t["status"] == "completed"])
+ in_progress = len([t for t in self.todos if t["status"] == "in_progress"])
+ total = len(self.todos)
+
+ print(f"\nProgress: {completed}/{total} completed")
+ print(f"Currently working on: {in_progress} task(s)\n")
+
+ for i, todo in enumerate(self.todos):
+ icon = (
+ "✅"
+ if todo["status"] == "completed"
+ else "🔧"
+ if todo["status"] == "in_progress"
+ else "❌"
+ )
+ text = (
+ todo["activeForm"]
+ if todo["status"] == "in_progress"
+ else todo["content"]
+ )
+ print(f"{i + 1}. {icon} {text}")
+
+ async def track_query(self, prompt: str):
+ try:
+ async for message in query(
+ prompt=prompt,
+ # Re-enable TodoWrite, which this tracker watches for.
+ options=ClaudeAgentOptions(max_turns=20, env={"CLAUDE_CODE_ENABLE_TASKS": "0"}),
+ ):
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, ToolUseBlock) and block.name == "TodoWrite":
+ self.todos = block.input["todos"]
+ self.display_progress()
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result,
+ # such as when the max_turns limit is hit.
+ print(f"Session ended with an error: {error}")
+
+ # Usage
+ async def main():
+ tracker = TodoTracker()
+ await tracker.track_query("Build a complete authentication system with todos")
+
+ asyncio.run(main())
##
@@ -191,6 +285,37 @@
console.log(`Session ended with an error: ${error}`);
}
+ import asyncio
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock
+
+ async def main():
+ try:
+ async for message in query(
+ prompt="Optimize my React app performance and track progress with todos",
+ options=ClaudeAgentOptions(max_turns=15),
+ ):
+ if not isinstance(message, AssistantMessage):
+ continue
+ for block in message.content:
+ if not isinstance(block, ToolUseBlock):
+ continue
+ if block.name == "TaskCreate":
+ print(f"+ {block.input['subject']}")
+ elif block.name == "TaskUpdate" and block.input.get("status"):
+ task_id = (
+ block.input.get("taskId")
+ or block.input.get("id")
+ or block.input.get("task_id")
+ )
+ if task_id:
+ print(f" {task_id} -> {block.input['status']}")
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result.
+ print(f"Session ended with an error: {error}")
+
+ asyncio.run(main())
+
##
--- a/tool-search.md
+++ b/tool-search.md
@@ -60,6 +60,34 @@
}
}
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ async def main():
+ options = ClaudeAgentOptions(
+ mcp_servers={
+ "enterprise-tools": {
+ "type": "http",
+ "url": "https://tools.example.com/mcp",
+ }
+ },
+ allowed_tools=[
+ "mcp__enterprise-tools__*"
+ ], # Wildcard pre-approves all tools from this server
+ env={
+ "ENABLE_TOOL_SEARCH": "auto:5" # Activate tool search when tools exceed 5% of context
+ },
+ )
+
+ async for message in query(
+ prompt="Find and run the appropriate database query",
+ options=options,
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+
+ asyncio.run(main())
+
Setting `ENABLE_TOOL_SEARCH` to `"false"` disables tool search and loads all tool definitions into context on every turn. This removes the search round-trip, which can be faster when the tool set is small (fewer than ~10 tools) and the definitions fit comfortably in the context window.
##
--- a/tools-reference.md
+++ b/tools-reference.md
@@ -11,7 +11,7 @@
`CronList`| Lists all scheduled tasks in the session| No
`Edit`| Makes targeted edits to specific files. See Edit tool behavior| Yes
`EnterPlanMode`| Switches to plan mode to design an approach before coding| No
-`EnterWorktree`| Creates an isolated [git worktree](</docs/en/worktrees>) and switches into it. Pass a `path` to switch into an existing worktree of the current repository instead of creating a new one. From within a worktree session, or from a subagent with a pinned working directory such as [`isolation: worktree`](</docs/en/sub-agents#supported-frontmatter-fields>), only the `path` form is available and the target must be under `.claude/worktrees/`| No
+`EnterWorktree`| Creates an isolated [git worktree](</docs/en/worktrees>) and switches into it. Pass a `path` to switch into an existing worktree instead of creating a new one. On first entry the target may be a worktree of the current repository or, in a multi-repo workspace, of a repository nested inside it. Before v2.1.203, a nested repository’s worktree was rejected. From within a worktree session, or from a subagent with a pinned working directory such as [`isolation: worktree`](</docs/en/sub-agents#supported-frontmatter-fields>), only the `path` form is available and the target must be under `.claude/worktrees/` of the session’s repository| No
`ExitPlanMode`| Presents a plan for approval and exits plan mode| Yes
`ExitWorktree`| Exits a worktree session and returns to the original directory. Not available to subagents that already run in their own working directory, such as with [`isolation: worktree`](</docs/en/sub-agents#supported-frontmatter-fields>)| No
`Glob`| Finds files based on pattern matching. See Glob tool behavior| No
@@ -34,8 +34,8 @@
`TaskCreate`| Creates a new task in the task list| No
`TaskGet`| Retrieves full details for a specific task| No
`TaskList`| Lists all tasks with their current status| No
-`TaskOutput`| (Deprecated) Retrieves output from a background task. Prefer `Read` on the task’s output file path| No
-`TaskStop`| Stops a running background task by ID. As of v2.1.198, also accepts an [agent-team teammate](</docs/en/agent-teams>) or a named background agent by agent ID or name| No
+`TaskOutput`| Retrieves output from a background task. Deprecated in favor of `Read` on the task’s output file path. When no task matches the ID, the error lists the running background agents by ID and description. Before v2.1.203, the error named only the missing ID| No
+`TaskStop`| Stops a running background task by ID. It also accepts an [agent-team teammate](</docs/en/agent-teams>) or a named background agent by agent ID or name. Before v2.1.198, it accepted only a background task ID. When no task matches the ID, the error lists the running background agents by ID and description, including agents that another agent spawned. Before v2.1.203, the error listed running teammates and named agents but not background agents another agent spawned, so those couldn’t be identified or stopped from the main conversation| No
`TaskUpdate`| Updates task status, dependencies, details, or deletes tasks| No
`TodoWrite`| Manages the session task checklist. Disabled by default as of v2.1.142 in favor of `TaskCreate`, `TaskGet`, `TaskList`, and `TaskUpdate`. Set `CLAUDE_CODE_ENABLE_TASKS=0` to re-enable| No
`ToolSearch`| Searches for and loads deferred tools when [tool search](</docs/en/mcp#scale-with-mcp-tool-search>) is enabled| No
--- a/typescript.md
+++ b/typescript.md
@@ -644,7 +644,7 @@
* **Applied on the next turn** : `model`, `effortLevel`, `ultracode`, `permissions`, `hooks`, `skillOverrides`, `fastMode`, `awaySummaryEnabled`, `agent`. Switching `agent` also applies that agent’s model override, hooks, and system prompt on the next turn.
* **No effect mid-session** : the system prompt options. These are resolved once at startup, so the running session keeps the original value even though the call succeeds. To change them, start a new session.
-The values are written to the flag-settings layer, the same layer the inline `settings` option of `query()` populates at startup. Flag settings sit near the top of the [settings precedence order](</docs/en/settings#settings-precedence>): they override user, project, and local settings, and only managed policy settings can override them. This is the same tier the on-page precedence section calls programmatic options. Successive calls shallow-merge top-level keys. A second call with `{ permissions: {...} }` replaces the entire `permissions` object from the prior call rather than deep-merging into it. To clear a key from the flag layer and fall back to lower-precedence sources, pass `null` for that key. Passing `undefined` has no effect because JSON serialization drops it. Only available in streaming input mode, the same constraint as `setModel()` and `setPermissionMode()`. The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify.
+`effortLevel` accepts an [effort level](</docs/en/model-config#adjust-effort-level>) name. It also accepts `"ultracode"`, which runs the session at `xhigh` effort and turns on [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>). The `Settings` type declares `effortLevel` without that value, so pass the equivalent `{ ultracode: true }` in TypeScript. The `ultracode` value requires Claude Code v2.1.203 or later and is accepted only by `applyFlagSettings()`, not by the `effortLevel` key in a settings file. The values are written to the flag-settings layer, the same layer the inline `settings` option of `query()` populates at startup. Flag settings sit near the top of the [settings precedence order](</docs/en/settings#settings-precedence>): they override user, project, and local settings, and only managed policy settings can override them. This is the same tier the on-page precedence section calls programmatic options. Successive calls shallow-merge top-level keys. A second call with `{ permissions: {...} }` replaces the entire `permissions` object from the prior call rather than deep-merging into it. To clear a key from the flag layer and fall back to lower-precedence sources, pass `null` for that key. Passing `undefined` has no effect because JSON serialization drops it. Only available in streaming input mode, the same constraint as `setModel()` and `setPermissionMode()`. The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify.
const q = query({ prompt: messageStream });
@@ -1097,6 +1097,7 @@
| SDKTaskStartedMessage
| SDKTaskProgressMessage
| SDKTaskUpdatedMessage
+ | SDKBackgroundTasksChangedMessage
| SDKSessionStateChangedMessage
| SDKWorkerShuttingDownMessage
| SDKCommandsChangedMessage
@@ -1110,7 +1111,8 @@
| SDKPromptSuggestionMessage
| SDKAPIRetryMessage
| SDKMirrorErrorMessage
- | SDKInformationalMessage;
+ | SDKInformationalMessage
+ | SDKConversationResetMessage;
###
@@ -2401,7 +2403,7 @@
path?: string;
};
-Creates and enters a temporary git worktree for isolated work. Pass `path` to switch into an existing worktree of the current repository instead of creating a new one. `name` and `path` are mutually exclusive.
+Creates and enters a temporary git worktree for isolated work. Pass `path` to switch into an existing worktree instead of creating a new one. On first entry the target must be a registered worktree of the current repository or, in a multi-repo workspace, of a repository nested inside it; from within a worktree session it must be under `.claude/worktrees/` of the session’s repository. `name` and `path` are mutually exclusive.
##
@@ -3649,6 +3651,26 @@
+`SDKBackgroundTasksChangedMessage`
+
+Emitted whenever the set of live background tasks changes: a task starts, completes, is killed, or a foreground agent is backgrounded. The `tasks` array is the full live set. Replace any cached set with each payload instead of pairing `task_started` and `task_notification` events, so the next membership change corrects any event you missed. Ordering relative to those per-task events is unspecified, so don’t correlate the two streams. Nothing is emitted at startup. Reset to an empty set whenever the session’s CLI process starts or restarts and let the next membership change repopulate it. Requires Claude Code v2.1.203 or later.
+
+ type SDKBackgroundTasksChangedMessage = {
+ type: "system";
+ subtype: "background_tasks_changed";
+ tasks: {
+ task_id: string;
+ task_type: string;
+ description: string;
+ }[];
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
`SDKFilesPersistedEvent`
Emitted when file checkpoints are persisted to disk.
@@ -3733,6 +3755,23 @@
uuid: UUID;
session_id: string;
};
+
+###
+
+
+
+`SDKConversationResetMessage`
+
+Emitted when the session’s conversation is replaced without ending the session, such as after `/clear`, on plan-mode exit, or when a fresh conversation starts. Mount an empty transcript under `new_conversation_id` and discard any cached session title.
+
+ type SDKConversationResetMessage = {
+ type: "conversation_reset";
+ new_conversation_id: UUID;
+ uuid: UUID;
+ session_id: string;
+ };
+
+The SDK’s published typings declare `SDKConversationResetMessage` in Claude Code v2.1.203 and later. Before v2.1.203, `SDKMessage` referenced the type without declaring it, so narrowing on `type === "conversation_reset"` failed to typecheck when `skipLibCheck` was disabled.
###
Show diff (312 lines)
--- a/user-input.md
+++ b/user-input.md
@@ -17,6 +17,13 @@
...
options = ClaudeAgentOptions(can_use_tool=handle_tool_request)
+
+ async function handleToolRequest(toolName, input, options) {
+ // options includes { signal: AbortSignal, suggestions?: PermissionUpdate[] }
+ // Prompt user and return allow or deny
+ }
+
+ const options = { canUseTool: handleToolRequest };
The callback fires in two cases:
@@ -115,6 +122,53 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+ import * as readline from "readline";
+
+ // Helper to prompt user for input in the terminal
+ function prompt(question: string): Promise<string> {
+ const rl = readline.createInterface({
+ input: process.stdin,
+ output: process.stdout
+ });
+ return new Promise((resolve) =>
+ rl.question(question, (answer) => {
+ rl.close();
+ resolve(answer);
+ })
+ );
+ }
+
+ for await (const message of query({
+ prompt: "Create a test file in /tmp and then delete it",
+ options: {
+ canUseTool: async (toolName, input) => {
+ // Display the tool request
+ console.log(`\nTool: ${toolName}`);
+ if (toolName === "Bash") {
+ console.log(`Command: ${input.command}`);
+ if (input.description) console.log(`Description: ${input.description}`);
+ } else {
+ console.log(`Input: ${JSON.stringify(input, null, 2)}`);
+ }
+
+ // Get user approval
+ const response = await prompt("Allow this action? (y/n): ");
+
+ // Return allow or deny based on user's response
+ if (response.toLowerCase() === "y") {
+ // Allow: tool executes with the original (or modified) input
+ return { behavior: "allow", updatedInput: input };
+ } else {
+ // Deny: tool doesn't execute, Claude sees the message
+ return { behavior: "deny", message: "User denied this action" };
+ }
+ }
+ }
+ })) {
+ if ("result" in message) console.log(message.result);
+ }
+
In Python, `can_use_tool` requires [streaming mode](</docs/en/agent-sdk/streaming-vs-single-mode>). When you pass a finite message stream through `query(prompt=generator)` or `ClaudeSDKClient.connect(prompt=async_iterable)`, the SDK closes the input stream after the last message, before the permission callback can be invoked, unless a registered hook or in-process MCP server is keeping it open. The example above keeps it open with a `PreToolUse` hook that returns `{"continue_": True}`. Connecting with no prompt and sending messages through `ClaudeSDKClient.query()` keeps the stream open on its own and needs no hook.
This example uses a `y/n` flow where any input other than `y` is treated as a denial. In practice, you might build a richer UI that lets users modify the request, provide feedback, or redirect Claude entirely. See Respond to tool requests for all the ways you can respond.
@@ -145,6 +199,12 @@
# Block the tool
return PermissionResultDeny(message="User rejected this action")
+
+ // Allow the tool to execute
+ return { behavior: "allow", updatedInput: input };
+
+ // Block the tool
+ return { behavior: "deny", message: "User rejected this action" };
Beyond allowing or denying, you can modify the tool’s input or provide context that helps Claude adjust its approach:
@@ -180,6 +240,16 @@
if approved:
return PermissionResultAllow(updated_input=input_data)
return PermissionResultDeny(message="User declined")
+
+ canUseTool: async (toolName, input) => {
+ console.log(`Claude wants to use ${toolName}`);
+ const approved = await askUser("Allow this action?");
+
+ if (approved) {
+ return { behavior: "allow", updatedInput: input };
+ }
+ return { behavior: "deny", message: "User declined" };
+ };
The user approves but wants to modify the request first. You can change the input before the tool executes. Claude sees the result but isn’t told you changed anything. Useful for sanitizing parameters, adding constraints, or scoping access.
@@ -196,6 +266,18 @@
)
return PermissionResultAllow(updated_input=sandboxed_input)
return PermissionResultAllow(updated_input=input_data)
+
+ canUseTool: async (toolName, input) => {
+ if (toolName === "Bash") {
+ // User approved, but scope all commands to sandbox
+ const sandboxedInput = {
+ ...input,
+ command: input.command.replace("/tmp", "/tmp/sandbox")
+ };
+ return { behavior: "allow", updatedInput: sandboxedInput };
+ }
+ return { behavior: "allow", updatedInput: input };
+ };
The user approves and doesn’t want to be asked again for this kind of call. The third callback argument carries `suggestions`, an array of ready-made [`PermissionUpdate`](</docs/en/agent-sdk/typescript#permissionupdate>) entries. Echo one back in `updatedPermissions` to apply it. A suggestion with the `localSettings` destination writes the rule to `.claude/settings.local.json` so future sessions skip the prompt for matching calls.The Python example requires `claude-agent-sdk` 0.1.80 or later.
@@ -217,6 +299,25 @@
return PermissionResultAllow(updated_input=input_data)
return PermissionResultDeny(message="User declined")
+ canUseTool: async (toolName, input, { suggestions = [] }) => {
+ const choice = await askUser(`Allow ${toolName}?`, ["once", "always", "no"]);
+
+ if (choice === "always") {
+ const persist = suggestions.filter(
+ (s) => s.destination === "localSettings"
+ );
+ return {
+ behavior: "allow",
+ updatedInput: input,
+ updatedPermissions: persist
+ };
+ }
+ if (choice === "once") {
+ return { behavior: "allow", updatedInput: input };
+ }
+ return { behavior: "deny", message: "User declined" };
+ };
+
The user doesn’t want this action to happen. Block the tool and provide a message explaining why. Claude sees this message and may try a different approach.
Python
@@ -229,6 +330,18 @@
if not approved:
return PermissionResultDeny(message="User rejected this action")
return PermissionResultAllow(updated_input=input_data)
+
+ canUseTool: async (toolName, input) => {
+ const approved = await askUser(`Allow ${toolName}?`);
+
+ if (!approved) {
+ return {
+ behavior: "deny",
+ message: "User rejected this action"
+ };
+ }
+ return { behavior: "allow", updatedInput: input };
+ };
The user doesn’t want this specific action, but has a different idea. Block the tool and include guidance in your message. Claude will read this and decide how to proceed based on your feedback.
@@ -243,6 +356,18 @@
message="User doesn't want to delete files. They asked if you could compress them into an archive instead."
)
return PermissionResultAllow(updated_input=input_data)
+
+ canUseTool: async (toolName, input) => {
+ if (toolName === "Bash" && input.command.includes("rm")) {
+ // User doesn't want to delete, suggest archiving instead
+ return {
+ behavior: "deny",
+ message:
+ "User doesn't want to delete files. They asked if you could compress them into an archive instead."
+ };
+ }
+ return { behavior: "allow", updatedInput: input };
+ };
For a complete change of direction (not just a nudge), use [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>) to send Claude a new instruction directly. This bypasses the current tool request and gives Claude entirely new instructions to follow.
@@ -278,6 +403,19 @@
):
print(message)
+ for await (const message of query({
+ prompt: "Analyze this codebase",
+ options: {
+ // Include AskUserQuestion in your tools list
+ tools: ["Read", "Glob", "Grep", "AskUserQuestion"],
+ canUseTool: async (toolName, input) => {
+ // Handle clarifying questions here
+ }
+ }
+ })) {
+ console.log(message);
+ }
+
2
Detect AskUserQuestion
@@ -294,6 +432,15 @@
return await handle_clarifying_questions(input_data)
# Handle other tools normally
return await prompt_for_approval(tool_name, input_data)
+
+ canUseTool: async (toolName, input) => {
+ if (toolName === "AskUserQuestion") {
+ // Your implementation to collect answers from the user
+ return handleClarifyingQuestions(input);
+ }
+ // Handle other tools normally
+ return promptForApproval(toolName, input);
+ };
3
@@ -359,6 +506,17 @@
}
)
+ return {
+ behavior: "allow",
+ updatedInput: {
+ questions: input.questions,
+ answers: {
+ "How should I format the output?": "Summary",
+ "Which sections should I include?": "Introduction, Conclusion"
+ }
+ }
+ };
+
###
@@ -564,6 +722,74 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+ import * as readline from "readline/promises";
+
+ // Helper to prompt user for input in the terminal
+ async function prompt(question: string): Promise<string> {
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
+ const answer = await rl.question(question);
+ rl.close();
+ return answer;
+ }
+
+ // Parse user input as option number(s) or free text
+ function parseResponse(response: string, options: any[]): string {
+ const indices = response.split(",").map((s) => parseInt(s.trim()) - 1);
+ const labels = indices
+ .filter((i) => !isNaN(i) && i >= 0 && i < options.length)
+ .map((i) => options[i].label);
+ return labels.length > 0 ? labels.join(", ") : response;
+ }
+
+ // Display Claude's questions and collect user answers
+ async function handleAskUserQuestion(input: any) {
+ const answers: Record<string, string> = {};
+
+ for (const q of input.questions) {
+ console.log(`\n${q.header}: ${q.question}`);
+
+ const options = q.options;
+ options.forEach((opt: any, i: number) => {
+ console.log(` ${i + 1}. ${opt.label} - ${opt.description}`);
+ });
+ if (q.multiSelect) {
+ console.log(" (Enter numbers separated by commas, or type your own answer)");
+ } else {
+ console.log(" (Enter a number, or type your own answer)");
+ }
+
+ const response = (await prompt("Your choice: ")).trim();
+ answers[q.question] = parseResponse(response, options);
+ }
+
+ // Return the answers to Claude (must include original questions)
+ return {
+ behavior: "allow",
+ updatedInput: { questions: input.questions, answers }
+ };
+ }
+
+ async function main() {
+ for await (const message of query({
+ prompt: "Help me decide on the tech stack for a new mobile app",
+ options: {
+ canUseTool: async (toolName, input) => {
+ // Route AskUserQuestion to our question handler
+ if (toolName === "AskUserQuestion") {
+ return handleAskUserQuestion(input);
+ }
+ // Auto-approve other tools for this example
+ return { behavior: "allow", updatedInput: input };
+ }
+ }
+ })) {
+ if ("result" in message) console.log(message.result);
+ }
+ }
+
+ main();
+
##
--- a/vs-code.md
+++ b/vs-code.md
@@ -87,6 +87,7 @@
* **Plan mode** : Claude describes what it will do and waits for approval before making changes. VS Code automatically opens the plan as a full markdown document where you can add inline comments to give feedback before Claude begins.
* **Edit automatically** : Claude makes edits without asking.
* **Command menu** : click `/` or type `/` to open the command menu. Options include attaching files, switching models, toggling extended thinking, viewing plan usage (`/usage`), and starting a [Remote Control](</docs/en/remote-control>) session (`/remote-control`). The Customize section provides access to MCP servers, hooks, memory, permissions, and plugins. Items with a terminal icon open in the integrated terminal.
+ * The Settings section includes **Enable Remote Control for all sessions** , which sets [`remoteControlAtStartup`](</docs/en/settings#available-settings>) so [every new interactive session connects to Remote Control automatically](</docs/en/remote-control#enable-remote-control-for-all-sessions>). Requires Claude Code v2.1.203 or later.
* **Context indicator** : the prompt box shows how much of Claude’s context window you’re using. Claude automatically compacts when needed, or you can run `/compact` manually.
* **Extended thinking** : lets Claude spend more time reasoning through complex problems. Toggle it on via the command menu (`/`). Claude’s reasoning appears in the conversation as collapsed blocks: click a block to read it, or press `Ctrl+O` to expand or collapse every thinking block in the session. See [Extended thinking](</docs/en/model-config#extended-thinking>) for details.
* **Multi-line input** : press `Shift+Enter` to add a new line without sending. This also works in the “Other” free-text input of question dialogs.
--- a/workflows.md
+++ b/workflows.md
@@ -134,7 +134,7 @@
/effort ultracode
-With ultracode on, Claude decides when a task warrants a workflow. A single request can turn into several workflows in a row: one to understand the code, one to make the change, and one to verify it. This applies to every task in the session, so each request uses more tokens and takes longer than at lower effort levels. Ultracode lasts for the current session and resets when you start a new one. Drop back with `/effort high` when you return to routine work. It’s available on models that support `xhigh` [effort](</docs/en/model-config#adjust-effort-level>); on other models the `/effort` menu doesn’t offer it.
+To start a session with ultracode already on, launch with `claude --effort ultracode`. Requires Claude Code v2.1.203 or later. With ultracode on, Claude decides when a task warrants a workflow. A single request can turn into several workflows in a row: one to understand the code, one to make the change, and one to verify it. This applies to every task in the session, so each request uses more tokens and takes longer than at lower effort levels. Ultracode lasts for the current session and resets when you start a new one. Drop back with `/effort high` when you return to routine work. It’s available on models that support `xhigh` [effort](</docs/en/model-config#adjust-effort-level>); on other models the `/effort` menu doesn’t offer it.
###
@@ -322,7 +322,12 @@
Cost
-A workflow spawns many agents, so a single run can use meaningfully more tokens than working through the same task in conversation. Runs count toward your plan’s usage and rate limits like any other session. To gauge the spend before committing to a large task, run the workflow on a small slice first: one directory instead of the whole repo, or a narrow question instead of a broad one. The `/workflows` view shows each agent’s token usage as the run progresses, and you can stop the run there at any time without losing completed work. The runtime’s agent caps limit how many agents a single run can spawn, which bounds the cost of a runaway script. To keep every run smaller by default, set a size guideline in `/config`. Every agent in a workflow uses your session’s model unless the script routes a stage to a different one. To control the model cost:
+A workflow spawns many agents, so a single run can use meaningfully more tokens than working through the same task in conversation. Runs count toward your plan’s usage and rate limits like any other session. To gauge the spend before committing to a large task, run the workflow on a small slice first: one directory instead of the whole repo, or a narrow question instead of a broad one. The `/workflows` view shows each agent’s token usage as the run progresses, and you can stop the run there at any time without losing completed work. The runtime’s agent caps limit how many agents a single run can spawn, which bounds the cost of a runaway script. To keep every run smaller by default, set a size guideline in `/config`. Claude Code also flags a run that grows unusually large. When a workflow schedules more than 25 agents, or its projected token total passes 1.5 million, its progress line in the task panel below the input box shows a `Large workflow` warning. The warning points you to `/workflows`, where you can stop the run. Requires Claude Code v2.1.203 or later. The warning is advisory: it doesn’t pause or limit the run. Two settings change when you see it:
+
+ * If you set a size guideline, the guideline’s agent count replaces the 25-agent threshold.
+ * Sessions with ultracode on don’t show the warning, because turning ultracode on already opts you in to large runs.
+
+Every agent in a workflow uses your session’s model unless the script routes a stage to a different one. To control the model cost:
* Check `/model` before a large run if you usually switch to a smaller model for routine work
* Ask Claude to use a smaller model for stages that don’t need the strongest one when you describe the task