Changes on
56 changes detected
--- a/admin-setup.md
+++ b/admin-setup.md
@@ -71,7 +71,7 @@
[Version floor](</docs/en/settings>)| Prevent auto-update from installing below an org-wide minimum| `minimumVersion`
[Required version range](</docs/en/settings>)| Refuse to start at all when the running version is outside an org-approved range. Stronger than `minimumVersion`, which only blocks downgrades| `requiredMinimumVersion`, `requiredMaximumVersion`
-Permission rules and sandboxing cover different layers. Denying WebFetch blocks Claude’s fetch tool, but if Bash is allowed, `curl` and `wget` can still reach any URL. Sandboxing closes that gap with a network domain allowlist enforced at the OS level. For the threat model these controls defend against, see [Security](</docs/en/security>).
+Organizations whose members authenticate through claude.ai or the Anthropic API can also govern models without deploying settings: [organization model restrictions](</docs/en/model-config#organization-model-restrictions>) disable individual models, an [organization default model](</docs/en/model-config#organization-default-model>) sets which model new sessions start on, and [organization effort limits](</docs/en/model-config#organization-effort-limits>) cap effort levels per role. All three controls require a Claude Enterprise plan. Model restrictions and effort limits are enforced server-side; the default model is a starting point that users can change, unless the organization enforces it. Enforcement is available to a limited set of organizations; ask your Anthropic account team about availability. None of these controls reach sessions on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or [Claude Platform on AWS](</docs/en/claude-platform-on-aws>); on those providers, use `availableModels` above for restrictions and the `model` key in managed settings for a default. Permission rules and sandboxing cover different layers. Denying WebFetch blocks Claude’s fetch tool, but if Bash is allowed, `curl` and `wget` can still reach any URL. Sandboxing closes that gap with a network domain allowlist enforced at the OS level. For the threat model these controls defend against, see [Security](</docs/en/security>).
##
--- a/advisor.md
+++ b/advisor.md
@@ -75,7 +75,8 @@
Haiku 4.5| Fable, Opus, Sonnet| Haiku can call the advisor but cannot act as one
Sonnet 4.6| Fable, Opus, Sonnet|
Sonnet 5| Fable, Opus, Sonnet 5| A Sonnet 4.6 advisor is rejected
-Opus 4.6 or later| Fable, Opus at or above the main model’s version| An Opus 4.7 main with an Opus 4.6 advisor is rejected. An Opus 4.6 main also accepts a Sonnet 5 advisor
+Opus 4.6| Fable, Opus, Sonnet 5| Sonnet 5 and Opus 4.6 are ranked as equally capable, so an Opus 4.6 main accepts a Sonnet 5 advisor
+Opus 4.7 or later| Fable, Opus 4.7, Opus 4.8| Opus 4.7 and Opus 4.8 are ranked as equally capable, so either accepts the other as an advisor. An Opus 4.7 main with an Opus 4.6 or Sonnet 5 advisor is rejected
Fable 5 (v2.1.170+)| Fable| An Opus or Sonnet advisor is rejected
Fable 5 requires Claude Code v2.1.170 or later and Fable 5 access, whether it acts as the main model or the advisor. Set the advisor as `opus`, `sonnet`, or `fable`. These aliases resolve to the latest version of each model. You can also pass a full model ID such as `claude-opus-4-8`. Subagents inherit the configured advisor and apply the same pairing check against their own model. Claude Code validates the pairing before sending a request:
@@ -154,7 +155,7 @@
/advisor off
-To disable the advisor tool entirely, including the `/advisor` command and the `--advisor` flag, set `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1`. See [Environment variables](</docs/en/env-vars>).
+To disable the advisor tool entirely, set `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1`. The `/advisor` command becomes unavailable and any configured `advisorModel` is ignored. The `--advisor` flag is accepted but has no effect; existing scripts that pass it continue to work without errors. See [Environment variables](</docs/en/env-vars>).
##
--- a/agent-teams.md
+++ b/agent-teams.md
@@ -71,7 +71,7 @@
* **Enter** : open the selected teammate’s transcript and message it directly
* **Escape** : interrupt the selected teammate’s current turn
-As of v2.1.181, an idle teammate’s row hides after 30 seconds and reappears on its next turn. The teammate stays running and addressable while hidden. If you want each teammate in its own split pane, see Choose a display mode.
+As of v2.1.199, an idle teammate’s row stays in the panel while any teammate or subagent is still working, so you can select it to review its transcript or send it more work. Once every agent in the panel is idle, idle rows hide after 30 seconds and reappear on the teammate’s next turn; the teammate stays running and addressable while hidden. In v2.1.181 through v2.1.198, an idle row hid 30 seconds after its own turn ended, even while other teammates were still working; idle rows are not hidden on versions before v2.1.181. When more than three teammates are idle at once, the rows beyond the first three collapse into a single row that counts the collapsed teammates, such as `2 idle agents` when five are idle. Select it and press Enter to expand the collapsed rows, or press Esc to collapse them again. Working teammates, failed teammates, and the teammate you’re viewing always keep their own rows. If you want each teammate in its own split pane, see Choose a display mode.
##
@@ -145,6 +145,8 @@
* **In-process mode** : use the up and down arrow keys in the agent panel to select a teammate, then press Enter to view its session and type to send it a message. Press `x` on a selected teammate to stop it. Press Ctrl+T to toggle the task list.
* **Split-pane mode** : click into a teammate’s pane to interact with their session directly. Each teammate has a full view of their own terminal.
+
+While you’re viewing an in-process teammate, plain text and [skills](</docs/en/skills>) go to that teammate, but built-in commands still run in the lead’s session. A teammate’s model and fast mode are fixed when it spawns, so `/model` and `/fast` only change the lead’s settings. As of v2.1.199, typing either command while viewing a teammate shows a notice that the change applies to the lead; earlier versions applied it to the lead with no indication. `/effort` still applies to the viewed teammate’s later turns, because teammates follow the lead’s [effort level](</docs/en/model-config#adjust-effort-level>).
###
@@ -257,7 +259,7 @@
Each teammate has its own context window. When spawned, a teammate loads the same project context as a regular session: CLAUDE.md, MCP servers, and skills. It also receives the spawn prompt from the lead. The lead’s conversation history does not carry over. **How teammates share information:**
* **Automatic message delivery** : when teammates send messages, they’re delivered automatically to recipients. The lead doesn’t need to poll for updates.
- * **Idle notifications** : when a teammate finishes and stops, they automatically notify the lead.
+ * **Idle notifications** : when a teammate finishes and stops, it automatically notifies the lead. As of v2.1.198, a teammate whose turn ends on an API error notifies the lead that it failed and includes the error text, instead of appearing to finish normally.
* **Shared task list** : all agents can see task status and claim available work.
* **Teammate messaging** : send a message to one specific teammate by name. To reach everyone, send one message per recipient.
@@ -404,7 +406,7 @@
If teammates aren’t appearing after you ask Claude to spawn them:
* In in-process mode, teammates appear in the agent panel below the prompt input. Use the up and down arrow keys to select one, then press Enter to view it.
- * A teammate row that disappeared after sitting idle has been hidden, not stopped. Idle rows hide after 30 seconds and reappear on the teammate’s next turn. Send the teammate a message by name to bring it back.
+ * A teammate row that disappeared after sitting idle has been hidden, not stopped. Idle rows hide 30 seconds after the whole panel goes idle and reappear on the teammate’s next turn. When more than three teammates are idle, their surplus rows collapse into a single `N idle agents` row that Enter expands. Send the teammate a message by name to bring a hidden row back.
* Check that the task you gave Claude was complex enough to warrant a team. Claude decides whether to spawn teammates based on the task.
* If you explicitly requested split panes, ensure tmux is installed and available in your PATH:
@@ -430,6 +432,8 @@
* Give them additional instructions directly
* Spawn a replacement teammate to continue the work
+
+As of v2.1.198, a message from the lead or another teammate wakes an in-process teammate that is waiting to retry a failed API request, so it retries immediately instead of waiting for the full retry delay.
###
@@ -463,6 +467,7 @@
* **Shutdown can be slow** : teammates finish their current request or tool call before shutting down, which can take time.
* **One team per session** : a session has exactly one team, scoped to that session. You can’t create additional named teams or share a team across sessions.
* **No nested teams** : teammates cannot spawn their own teammates. Only the lead can manage the team.
+ * **No background subagents from in-process teammates** : an in-process teammate’s own subagents run in the foreground. Asking for a background one, whether with `run_in_background` or a subagent definition that sets `background: true`, returns an error, because a teammate’s background work can’t outlive the lead’s process. Subagents launched from the main conversation follow the [background default](</docs/en/sub-agents#run-subagents-in-foreground-or-background>).
* **Lead is fixed** : the main session is the lead for its lifetime. You can’t promote a teammate to lead or transfer leadership.
* **Permissions set at spawn** : all teammates start with the lead’s permission mode. You can change individual teammate modes after spawning, but you can’t set per-teammate modes at spawn time.
* **Split panes require tmux or iTerm2** : the default in-process mode works in any terminal. Split-pane mode isn’t supported in VS Code’s integrated terminal, Windows Terminal, or Ghostty.
Show diff (184 lines)
--- a/agent-view.md
+++ b/agent-view.md
@@ -7,7 +7,7 @@
* Quick start: give Claude a task to work on in the background, check on it, and step in when needed
* Monitor sessions with agent view, including state icons, peeking and replying, attaching, organizing, and keyboard shortcuts
* Dispatch new agents from agent view, from inside a session, or from your shell
- * Manage sessions from the shell
+ * Manage sessions from the shell with `claude agents`, `claude attach`, and related commands
* How background sessions are hosted by the supervisor process
##
@@ -50,7 +50,7 @@
Bring an existing session in
-To move a session you already have open into agent view, run `/bg` inside it, or press `←` on an empty prompt to background it and open agent view in one step. The session keeps running and appears as a row alongside the ones you dispatched.
+This step needs a running session. If you followed the earlier steps you don’t have one open in this terminal, so open a regular `claude` session in another terminal and send it a message first. To move a session you already have open into agent view, run `/bg` inside it, or press `←` on an empty prompt to background it and open agent view in one step. The session keeps running and appears as a row alongside the ones you dispatched.
You can use `claude agents` as your primary entry point instead of `claude`: dispatch every task from agent view, attach when you want the full conversation, and press `←` to return to the table.
@@ -60,7 +60,7 @@
Monitor sessions with agent view
-Run `claude agents` to open agent view. It takes over the full terminal and lists every session grouped by state, with pinned sessions and the ones that need you at the top. Each row shows the session’s name, current activity, and how long ago it last changed. By default the list shows every background session you’ve started, across all your projects. A session working in one repository and another in a different worktree both appear here, regardless of which directory you opened agent view from. To narrow the list to one project, pass `--cwd`:
+Run `claude agents` to open agent view. It takes over the full terminal and lists every session grouped by state, with pinned sessions and the ones that need you at the top. Each row shows the session’s name, current activity, and how long ago it last changed. The name is tinted with the color set by [`/color`](</docs/en/commands>) in that session. As of v2.1.199 the color carries over when you background a session with `←` or `/background`. By default the list shows every background session you’ve started, across all your projects. A session working in one repository and another in a different worktree both appear here, regardless of which directory you opened agent view from. To narrow the list to one project, pass `--cwd`:
claude agents --cwd ~/projects/my-app
@@ -70,7 +70,7 @@
✽ clawd walk cycle Write assets/sprites/clawd-walk.png 3m
Ready for review
- ∙ jump physics Opened PR with collision fix PR #2048 2h
+ ∙ jump physics Opened PR with collision fix #2048 2h
Needs input
✻ power-up design needs input: double jump or wall climb? 1m
@@ -109,7 +109,7 @@
`∙`| The process has exited. You can still peek, reply, or attach, and Claude restarts from where it left off
`✢`| A [`/loop`](</docs/en/scheduled-tasks>) session sleeping between iterations. The row shows its run count and a countdown
-The `PR #N` label that can appear at the right edge of a row is the pull request the session opened, not part of the state icon. When a session has opened more than one pull request, the label shows a count instead, such as `3 PRs`. The terminal tab title shows the awaiting-input count while agent view is open: `2 awaiting input · claude agents` when sessions need input, or `claude agents` when none do. Background sessions don’t need any terminal open to keep working. A separate supervisor process runs them, so you can close agent view, close your shell, or start a new interactive session and your dispatched work keeps going. Session state persists on disk through auto-updates and supervisor restarts. Sessions are also preserved when your machine sleeps. Their processes resume on wake and the supervisor reconnects to them instead of treating the time gap as idle. Shutting down still stops running sessions; see Sessions show as failed after shutdown for how to recover them.
+The `#N` label that can appear at the right edge of a row is the pull request the session opened, not part of the state icon. The terminal tab title shows the awaiting-input count while agent view is open: `2 awaiting input · claude agents` when sessions need input, or `claude agents` when none do. As of v2.1.198, while agent view is open, Claude Code also sends a notification through your configured [terminal notification channel](</docs/en/terminal-config#get-a-terminal-bell-or-notification>) when a local background session starts needing your input, finishes, or fails. Sessions that run on a schedule, such as [`/loop`](</docs/en/scheduled-tasks>) sessions, notify only when they need your input. Notifications use the same [`preferredNotifChannel` setting](</docs/en/settings#available-settings>) as the rest of Claude Code and fire the [`Notification` hook](</docs/en/hooks#notification>) with the `agent_needs_input` or `agent_completed` type. Background sessions don’t need any terminal open to keep working. A separate supervisor process runs them, so you can close agent view, close your shell, or start a new interactive session and your dispatched work keeps going. Session state persists on disk through auto-updates and supervisor restarts. Sessions are also preserved when your machine sleeps. Their processes resume on wake and the supervisor reconnects to them instead of treating the time gap as idle. Shutting down still stops running sessions; see Sessions show as failed after shutdown for how to recover them.
###
@@ -125,7 +125,7 @@
Pull request status
-When a session opens a pull request, a `PR #1234` label appears at the right edge of the row, linked to the pull request in terminals that support hyperlinks. The label persists when you send a follow-up to the session, so the pull request remains visible while the row reverts to live progress. When a session has opened more than one pull request, the label shows a count instead, such as `3 PRs`, colored by the open pull request that most needs attention. Open the peek panel to see them all. The pull request number is colored by its status:
+When a session opens a pull request, a `#1234` label appears at the right edge of the row, linked to the pull request in terminals that support hyperlinks. The label persists when you send a follow-up to the session, so the pull request remains visible while the row reverts to live progress. Background sessions that isolated their changes in a worktree open these pull requests themselves; How file edits are isolated covers when that happens and what a session never does without asking. When a session has opened more than one pull request, the label shows a count instead, such as `3 PRs`, colored by the open pull request that most needs attention. Open the peek panel to see them all. The pull request number is colored by its status:
Color| Pull request status
---|---
@@ -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 to detach and return to agent view. If a dialog has focus and isn’t responding to `←`, press `Ctrl+Z` to detach immediately. `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 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`.
###
@@ -235,7 +235,14 @@
`#<number>` or a pull request URL| If a session is already working on that PR, select it instead of dispatching
`Shift+Enter`| Dispatch and immediately attach to the new session
-A small set of commands run in agent view itself instead of dispatching: `/exit` and `/quit` close agent view, `/logout` signs you out, and `/model` sets the dispatch model. 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.
+A small set of commands run in agent view itself instead of dispatching:
+
+ * `/exit` and `/quit` close agent view
+ * `/logout` signs you out
+ * `/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.
####
@@ -257,7 +264,7 @@
From inside a session
-Run `/background` or its alias `/bg` to move the current conversation into a background session. Pass a prompt such as `/bg run the test suite and fix any failures` to give one more instruction first. If Claude is responding when you run `/bg`, the response continues in the background session. Backgrounding from an interactive session starts a fresh process that resumes from the saved conversation, and in-flight work moves to it: running background shell commands, backgrounded subagents, dynamic workflows, and scheduled tasks you created with [`/loop`](</docs/en/scheduled-tasks>) carry over to the background session and keep running there. A subagent moves together with everything it started, so it carries over only when all of that work can move too, including on Windows. To stop in-flight work instead of carrying it over, set the [`CLAUDE_DISABLE_ADOPT=1`](</docs/en/env-vars#variables>) environment variable; Claude Code then asks you to confirm before backgrounding. Work that can’t carry over, such as a running [monitor](</docs/en/tools-reference#monitor-tool>), is stopped. A backgrounded subagent that owns a monitor is stopped along with it. When any such work is running, Claude Code shows a `Background this session?` dialog so you can confirm before it’s stopped. Once in the background, the session can start new subagents, monitors, and background commands, and those keep running across later detach and reattach. Configuration flags from the original launch carry through to the backgrounded session, so its MCP servers, settings, and fallback model remain in effect:
+Run `/background` or its alias `/bg` to move the current conversation into a background session. Pass a prompt such as `/bg run the test suite and fix any failures` to give one more instruction first. If Claude is responding when you run `/bg`, the response continues in the background session. Exiting an interactive session that still has background work running, such as subagents, background shell commands, workflows, or [monitors](</docs/en/tools-reference#monitor-tool>), shows a `Background work is running` dialog instead of quitting immediately. As of v2.1.198 the dialog offers `Move to background and exit` alongside `Exit anyway` and `Stay`. Choosing it moves the session to the background the same way `/background` does, then returns you to your shell, so work that can carry over keeps running and the session appears in agent view. The option isn’t shown when agent view is turned off. Backgrounding from an interactive session starts a fresh process that resumes from the saved conversation, and in-flight work moves to it: running background shell commands, backgrounded subagents, dynamic workflows, and scheduled tasks you created with [`/loop`](</docs/en/scheduled-tasks>) carry over to the background session and keep running there. A subagent moves together with everything it started, so it carries over only when all of that work can move too, including on Windows. To stop in-flight work instead of carrying it over, set the [`CLAUDE_DISABLE_ADOPT=1`](</docs/en/env-vars#variables>) environment variable; Claude Code then asks you to confirm before backgrounding. Work that can’t carry over, such as a running [monitor](</docs/en/tools-reference#monitor-tool>), is stopped. A backgrounded subagent that owns a monitor is stopped along with it. When any such work is running, Claude Code shows a `Background this session?` dialog so you can confirm before it’s stopped. Once in the background, the session can start new subagents, monitors, and background commands, and those keep running across later detach and reattach. Configuration flags from the original launch carry through to the backgrounded session, so its MCP servers, settings, and fallback model remain in effect:
* `--mcp-config` and `--strict-mcp-config`
* `--settings`
@@ -278,7 +285,7 @@
claude --bg "investigate the flaky SettingsChangeDetector test"
-To run a specific subagent as the session’s main agent, combine `--bg` with `--agent`:
+The prompt is the positional argument, not a `-p` value. As of v2.1.198, combining `--bg` with `-p` or `--print` is rejected with an error before any session is created, because `--print` never starts the interactive session that `claude agents` attaches to. To run a specific subagent as the session’s main agent, combine `--bg` with `--agent`:
claude --agent code-reviewer --bg "address review comments on PR 1234"
@@ -286,7 +293,7 @@
claude --bg --name "flaky-test-fix" "investigate the flaky SettingsChangeDetector test"
-After backgrounding, Claude prints the session’s short ID and the commands for managing it. When you pass `--name`, the name appears after the short ID:
+After backgrounding, Claude prints the session’s short ID and the commands for managing it. When the service that hosts background sessions isn’t already running, `--bg` may first print `Starting background service…` above this output. When you pass `--name`, the name appears after the short ID:
backgrounded · 7c5dcf5d · flaky-test-fix
claude agents list sessions
@@ -330,7 +337,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.
+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.
###
@@ -419,7 +426,13 @@
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 Bedrock, Vertex, and 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 shell commands and dynamic workflows the session started keep running when its process is stopped, restarted, or updated, including on Windows. The next process started for that session picks them back up, a shell command that finished in the meantime is reported as completed with its output, and a workflow resumes from where it left off. Shell commands started by a subagent and running [monitors](</docs/en/tools-reference#monitor-tool>) still stop with the process, and deleting the session stops everything it handed off. To stop background shell commands and workflows with the process too, set the [`CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF`](</docs/en/env-vars#variables>) environment variable to `1`. If a restarted session comes back showing only its original prompt because Claude Code misread its transcript as empty, the conversation transcript is renamed with an `.orphaned-` suffix instead of deleted, so it stays on your machine. An empty row left over from pressing `←` that was never given a prompt is removed entirely after about five minutes so the list clears on its own. Sessions started with `claude --bg` and sessions waiting on a setup prompt such as a trust dialog aren’t removed this way. When the host runs low on memory, the supervisor stops idle non-pinned sessions first and stops idle pinned ones only if that freed nothing. The supervisor watches the installed Claude Code binary on disk and restarts into the new version after the regular [auto-updater](</docs/en/setup#auto-updates>) replaces it. This is a local file watch, not a network check. Background sessions are detached processes, so they keep running through the restart and the new supervisor reconnects to them. An idle pinned session is also restarted in place onto the new version so it picks up the update without you reattaching.
+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 Bedrock, Vertex, and 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:
+
+ * 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
+ * A [background subagent](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) resumes from its own transcript
+
+As of v2.1.198 the handoff covers all three. Before v2.1.198 it covered only shell commands and workflows, so a background subagent stopped with the process and was reported as failed on the next wake. Work whose state lives only inside the process itself stops with it instead of being handed off. That’s shell commands a subagent started, which the resumed subagent can start again, and running [monitors](</docs/en/tools-reference#monitor-tool>), whose event stream can’t be moved to another process. Deleting the session stops everything it handed off. To stop all of the session’s background work with the process instead of handing it off, set the [`CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF`](</docs/en/env-vars#variables>) environment variable to `1`. If a restarted session comes back showing only its original prompt because Claude Code misread its transcript as empty, the conversation transcript is renamed with an `.orphaned-` suffix instead of deleted, so it stays on your machine. An empty row left over from pressing `←` that was never given a prompt is removed entirely after about five minutes so the list clears on its own. Sessions started with `claude --bg` and sessions waiting on a setup prompt such as a trust dialog aren’t removed this way. When the host runs low on memory, the supervisor stops idle non-pinned sessions first and stops idle pinned ones only if that freed nothing. The supervisor watches the installed Claude Code binary on disk and restarts into the new version after the regular [auto-updater](</docs/en/setup#auto-updates>) replaces it. This is a local file watch, not a network check. Background sessions are detached processes, so they keep running through the restart and the new supervisor reconnects to them. An idle pinned session is also restarted in place onto the new version so it picks up the update without you reattaching.
###
@@ -496,6 +509,14 @@
+A session fails before starting with a `possibly low memory` note
+
+As of v2.1.199, when a background session’s process exits before it finishes starting and the host is low on memory, the row’s status names the exit and adds `possibly low memory — free some up and retry`. Earlier versions showed only the bare exit reason for this failure. The note is a hypothesis, not a confirmed cause. Claude Code adds it only when the process exited silently, without writing an error and without being stopped by a signal, and the host reported low memory at that moment. When the process did write an error before exiting, the row shows that error instead. Free up memory on the machine, then attach, peek, or reply to the row and the supervisor starts a fresh process for the session. When memory stays low, the supervisor also stops idle sessions to free resources on its own.
+
+###
+
+
+
Agent view says the background service did not respond
If attaching, peeking, or `claude logs` reports that the background service did not respond, the supervisor process has likely stalled. Stop it and let the next `claude agents` start a fresh one. To keep your background sessions running through the restart, pass `--keep-workers`:
@@ -510,7 +531,7 @@
Dispatch fails with `Could not resolve authentication method`
-If a background dispatch fails with `Could not resolve authentication method` while interactive sessions authenticate normally, the worker that received the dispatch did not pick up credentials. The supervisor supplies a fresh credential snapshot when it assigns a pre-warmed worker, so this error means no stored credential was available to the supervisor process itself. Confirm you have run `/login` or configured an API key, then stop the supervisor:
+If a background dispatch fails with `Could not resolve authentication method` while interactive sessions authenticate normally, the worker that received the dispatch didn’t pick up credentials. The supervisor supplies a fresh credential snapshot when it assigns a pre-warmed worker, so this error means no stored credential was available to the supervisor process itself. Confirm you have run `/login` or configured an API key, then stop the supervisor:
claude daemon stop --any --keep-workers
@@ -520,9 +541,17 @@
-Background sessions cannot read Desktop, Documents, or Downloads on macOS
+Background sessions can’t read Desktop, Documents, or Downloads on macOS
On macOS, the background session host runs as its own process and requests access to protected folders separately from your terminal. If a background session reports `Operation not permitted` when reading `~/Desktop`, `~/Documents`, `~/Downloads`, or another protected location, grant access in System Settings under Privacy & Security > Files and Folders, or enable Full Disk Access for the entry. With the native installer, the entry appears as Claude Code and the grant persists across updates. With other install methods such as Homebrew or npm, the entry shows the binary path and may need to be granted again after updating.
+
+###
+
+
+
+Background sessions can’t reach local-network hosts on macOS
+
+On macOS 15 and later, the system blocks a process from reaching devices on your local network until you grant Local Network permission. Before v2.1.198 the background session host never requested that permission, so commands targeting a LAN address failed with `connect: no route to host` even though the same command worked in a foreground terminal. As of v2.1.198, the first command in a background session that connects to a local-network address triggers the macOS Local Network permission prompt for Claude Code. Grant it once and those commands reach LAN hosts the same way they do in a foreground terminal.
###
@@ -574,6 +603,8 @@
Version| Change
---|---
+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.
+v2.1.198| Agent view sends a notification through `preferredNotifChannel` when a background session needs input, finishes, or fails, and fires the `Notification` hook with the `agent_needs_input` or `agent_completed` type. `←` and `/exit` inside `claude attach <id>` return to agent view instead of exiting to the shell; `Ctrl+Z` returns to the shell. A background session that isolated its work in a worktree commits, pushes its own isolated branch, never `main` or `master`, and opens a draft pull request when it finishes instead of asking first. `/login` runs in agent view and opens the sign-in dialog. The `Background work is running` exit dialog offers `Move to background and exit`. The exit handoff also covers background subagents, which resume from their transcript on the next wake instead of being reported as failed. `claude --bg` combined with `-p` or `--print` is rejected with an error.
v2.1.196| A single `←` press backgrounds a foreground session; earlier versions required two presses, with a footer hint and a confirm. `--dangerously-skip-permissions` passed to `claude agents` shows the bypass disclaimer instead of being silently dropped. Interactive sessions you never named carry a default name such as `my-app-3f` in session listings and `claude agents --json`. Background shell commands and dynamic workflows survive the session’s process being stopped, restarted, or updated, including on Windows; set `CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF=1` to turn the handoff off. A transcript misread as empty on restart is renamed with an `.orphaned-` suffix instead of deleted.
v2.1.195| In-flight work carries over when you background a session on Windows too; set `CLAUDE_DISABLE_ADOPT=1` to stop it instead. The `Completed` group fills the remaining vertical space and the header compacts on short terminals. An older Claude Code version no longer drops newer sessions’ `state.json` fields or hides those sessions from `claude agents`. Attaching to a stopped session switches immediately instead of showing a blank screen for up to five seconds. A supervisor that can’t accept connections exits and releases its lock on its own.
v2.1.174| Background sessions no longer inherit gateway endpoint variables such as `ANTHROPIC_BASE_URL` from the supervisor’s launch shell; the supervisor supplies a fresh credential snapshot to pre-warmed workers, fixing spurious `Could not resolve authentication method` errors.
--- a/agents.md
+++ b/agents.md
@@ -45,7 +45,7 @@
The command for checking on running work depends on which approach you used:
* For background sessions, `claude agents` opens [agent view](</docs/en/agent-view>): one screen showing every session, its state, and which ones need your input.
- * For subagents in the current session, `/agents` opens a panel with a **Running** tab listing live subagents and a **Library** tab where you [create and edit custom subagents](</docs/en/sub-agents#use-the-%2Fagents-command>). Despite the similar name, this is separate from `claude agents`.
+ * For subagents in the current session, named background subagents appear in the @-mention typeahead with their status. As of v2.1.198, `/agents` no longer opens a panel; it prints a notice pointing to the subagent file locations. To [create and edit custom subagents](</docs/en/sub-agents#configure-subagents>), ask Claude or edit the files directly. Despite the similar name, `/agents` is separate from `claude agents`.
* For anything running in the background of the current session, `/tasks` lists each item and lets you check on, attach to, or stop it.
* For dynamic workflows, `/workflows` lists running and completed runs, the phase each is in, and how many agents have finished.
--- a/amazon-bedrock.md
+++ b/amazon-bedrock.md
@@ -104,7 +104,7 @@
Claude Code supports automatic credential refresh for AWS SSO and corporate identity providers. Add these settings to your Claude Code settings file (see [Settings](</docs/en/settings>) for file locations). These two settings have different trigger conditions:
- * **`awsAuthRefresh`** : runs only when Claude Code detects that your AWS credentials are expired, either locally based on their timestamp or when Bedrock returns a credential error, then retries the request with refreshed credentials.
+ * **`awsAuthRefresh`** : runs only when Claude Code detects that your AWS credentials are expired, either locally based on their timestamp or when the API returns a credential error, then retries the request with refreshed credentials.
* **`awsCredentialExport`** : runs at session start and on each credential reload, even when the credentials in your AWS default credential provider chain are still valid. Use this when your Bedrock account requires cross-account credentials that differ from the ones the default provider chain would resolve.
##### Example configuration
--- a/artifacts.md
+++ b/artifacts.md
@@ -1,6 +1,6 @@
-Artifacts require a Team or Enterprise plan and a session signed in with [`/login`](</docs/en/setup#authenticate>). See Availability for the full set of requirements.
-
-An artifact is a live, interactive web page that Claude Code publishes from your session to a private URL on claude.ai. You open it in a browser, and it updates in place as the session continues. Share it from the page header when you want a teammate to see it too. For example, use an artifact to walk a reviewer through a pull request with annotated diffs, build a dashboard from session data, or keep an investigation timeline that fills in as Claude works.
+Artifacts are available on Pro, Max, Team, and Enterprise plans and require a session signed in with [`/login`](</docs/en/setup#authenticate>). See Availability for the full set of requirements.
+
+An artifact is a live, interactive web page that Claude Code publishes from your session to a private URL on claude.ai. You open it in a browser, and it updates in place as the session continues. On Team and Enterprise plans, share it from the page header when you want a teammate to see it too. For example, use an artifact to walk a reviewer through a pull request with annotated diffs, build a dashboard from session data, or keep an investigation timeline that fills in as Claude works.
##
@@ -60,7 +60,7 @@
Share an artifact
-A new artifact is visible only to you. Open it in your browser and use the **Share** control in the page header to grant access to specific people in your organization, or to everyone in it. The header names you as the artifact’s author, so anyone you share it with can see who published the page. It also links to your gallery at [claude.ai/code/artifacts](<https://claude.ai/code/artifacts>), which lists every artifact you have created. Sharing stops at your organization. Viewers must sign in to claude.ai as a member of the same organization that published the artifact, and there is no option to make an artifact viewable outside it. To send the underlying content to someone outside your organization, ask Claude for the HTML file and share that file directly. Artifacts are viewable, not co-edited. People you share with see each version you publish but cannot change the page; you remain the only writer.
+A new artifact is visible only to you. On Pro and Max plans, artifacts stay private to you. On Team and Enterprise plans, open the artifact in your browser and use the **Share** control in the page header to grant access to specific people in your organization, or to everyone in it. The header names you as the artifact’s author, so anyone you share it with can see who published the page. It also links to your gallery at [claude.ai/code/artifacts](<https://claude.ai/code/artifacts>), which lists every artifact you have created. Sharing stops at your organization. Viewers must sign in to claude.ai as a member of the same organization that published the artifact, and there is no option to make an artifact viewable outside it. To send the underlying content to someone outside your organization, ask Claude for the HTML file and share that file directly. Artifacts are viewable, not co-edited. People you share with see each version you publish but cannot change the page; you remain the only writer.
##
@@ -168,7 +168,7 @@
Requirement| Available when
---|---
-Plan| Team or Enterprise. On Team plans, artifacts are on by default. On Enterprise plans, an Owner enables them in claude.ai admin settings.
+Plan| Pro, Max, Team, or Enterprise. On Pro and Max plans, artifacts are private to you, and no admin management applies. On Team plans, artifacts are on by default. On Enterprise plans, an Owner enables them in claude.ai admin settings.
Authentication| Signed in to claude.ai with `/login`. Sessions using an API key, [gateway token](</docs/en/llm-gateway>), or cloud-provider credential cannot publish.
Model provider| Anthropic API. Not available on [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud Vertex AI](</docs/en/google-vertex-ai>), or [Microsoft Foundry](</docs/en/microsoft-foundry>).
Organization policy| Customer-managed encryption keys (CMEK), HIPAA, and [Zero Data Retention](</docs/en/zero-data-retention>) are not enabled for the organization.
--- a/auto-mode-config.md
+++ b/auto-mode-config.md
@@ -36,12 +36,25 @@
Define trusted infrastructure
-For most organizations, `autoMode.environment` is the only field you need to set. It tells the classifier which repos, buckets, and domains are trusted: the classifier uses it to decide what “external” means, so any destination not listed is a potential exfiltration target. As of Claude Code v2.1.195, `claude auto-mode defaults` prints two kinds of environment entry.
-
+For most organizations, `autoMode.environment` is the only field you need to set. It tells the classifier which repos, buckets, and domains are trusted: the classifier uses it to decide what “external” means, so any destination not listed is a potential exfiltration target. As of Claude Code v2.1.198, `claude auto-mode defaults` prints three kinds of environment entry. Versions before v2.1.195 print only the first five trust slots.
+
+ * **Context slots** : describe your organization, stack, and security posture so the classifier reads the other rules in your context. Unlike the other two kinds, context slots have no rules of their own that target them. Each defaults to `None configured` or to the conservative assumption named next to it:
+ * **Organization**
+ * **Primary use of Claude Code** : defaults to software development
+ * **Cloud provider(s)**
+ * **Repository visibility** : a repository is assumed private unless its remote host and name indicate otherwise
+ * **Internal sharing / snippet hosting** : public paste and gist services are treated as outside the trust boundary until you name one
+ * **Org-specific CLIs**
+ * **Secrets management**
+ * **Default / protected branches** : `main` and `master` are treated as protected until you name others
+ * **CI/CD deploy targets**
+ * **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.
- * **Sensitivity slots** : name what the protective rules treat as high-risk. The slots are PII / regulated-data locations, 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.
-
-Versions before v2.1.195 print only the first five trust slots. 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.
+ * **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.
{
"autoMode": {
@@ -63,12 +76,12 @@
* **Trusted internal domains** : hostnames for APIs, dashboards, and services inside your network, like `*.internal.example.com`
* **Key internal services** : CI, artifact registries, internal package indexes, incident tooling
* **Internal package registry** : the private npm, PyPI, or other registry that installs should route through, so installs that bypass it for a public registry get blocked
- * **PII / regulated-data locations** : the buckets, databases, or paths that hold personal or regulated data, so the classifier protects those locations instead of guessing from content
+ * **Sensitive data locations & audiences**: the buckets, databases, or paths that hold personal data, confidential business data, credentials, regulated data, or similarly sensitive material, and the audiences that data in each location may be shared with, so the classifier protects those locations instead of guessing from content. Claude Code v2.1.195 through v2.1.197 name this entry PII / regulated-data locations and cover only locations that hold personal or regulated data, without the audience dimension
* **Sensitive remote targets** : the namespaces, hosts, or containers that count as production, so remote shells and port-forwards into them need your explicit approval
* **Protected IaC scopes** : the infrastructure resources whose apply or destroy should always require you to name the change
* **Additional context** : regulated-industry constraints, multi-tenant infrastructure, or compliance requirements that affect what the classifier should treat as risky
-The Internal package registry, PII / regulated-data locations, Sensitive remote targets, and Protected IaC scopes entries require Claude Code v2.1.195 or later. Earlier versions still read them as plain context but don’t have the built-in rules that target them. A useful starting template: fill in the bracketed fields and remove any lines that don’t apply.
+The Internal package registry, Sensitive data locations & audiences, Sensitive remote targets, and Protected IaC scopes entries require Claude Code v2.1.195 or later. Earlier versions still read them as plain context but don’t have the built-in rules that target them. A useful starting template: fill in the bracketed fields and remove any lines that don’t apply.
{
"autoMode": {
--- a/changelog.md
+++ b/changelog.md
@@ -2,10 +2,42 @@
+2.1.199
+
+July 2, 2026
+
+ * Stacked slash-skill invocations like `/skill-a /skill-b do XYZ` now load all leading skills (up to 5), not just the first
+ * Fixed SSL certificate errors (TLS-inspecting proxies, missing `NODE_EXTRA_CA_CERTS`, expired certs) burning retries before showing actionable guidance — they now fail immediately with the fix hint
+ * Fixed streaming responses being discarded when the API emits a mid-stream overloaded/server error after partial output — the partial is now kept with an incomplete-response notice
+ * Fixed subagents cut off by a rate limit or server error silently failing instead of returning their partial work to the parent
+ * Fixed subagents reporting API errors (e.g. usage limit reached) as successful results — the error is now reported to the parent agent
+ * Fixed the background-agent daemon on Linux killing itself and every running agent every ~50 seconds after an unclean shutdown left a corrupted worker record
+ * Fixed background agents failing to cold-start over SSH on macOS with “Could not switch to audit session” (regression in 2.1.196)
+ * Fixed `claude stop` being silently undone when it raced a background-agent respawn — the respawn now honors the stop
+ * Fixed background job progress indicators stalling for minutes while the job ran long commands
+ * Fixed background sessions on memory-starved machines showing a generic error — they now indicate low memory and suggest freeing resources
+ * Fixed remote sessions briefly flapping between Working and Idle in the agent view when a background agent completes
+ * Fixed idle subagents vanishing from the agent panel while other subagents were still working; surplus idle agents now collapse into an expandable summary row
+ * Fixed typing `/model` or `/fast` while viewing a subagent silently opening the lead’s model picker — a notice now explains the command applies to the lead
+ * Fixed `SessionStart`, `Setup`, and `SubagentStart` hooks silently hiding stderr when exiting with code 2 — the error is now shown in the transcript
+ * Fixed `claude --dangerously-skip-permissions daemon <subcommand>` being treated as a chat prompt instead of running the subcommand
+ * Fixed `SendMessage` silently misrouting when a re-spawned agent reuses a previous agent’s name — the tool now detects the mismatch and asks the caller to retarget
+ * Fixed opening or resuming a session with no new messages needlessly growing the transcript file
+ * Fixed backgrounding a session with `←` or `/background` dropping its `/color` from the agent view row
+ * Fixed resetting a corrupted config file from the startup recovery dialog destroying it unrecoverably — it now backs up the file first
+ * Fixed Claude in Chrome repeatedly opening the reconnect page when sessions run from different builds or config directories
+ * Fixed plan mode not prompting for state-changing browser tool calls; read-only `browser_batch` calls are now correctly auto-allowed
+ * Transient server rate-limit errors (429s unrelated to your usage limit) are now retried automatically with backoff for subscribers instead of failing the turn
+ * `CLAUDE_CODE_RETRY_WATCHDOG` now raises the default retry count for non-capacity transient errors to 300 and lifts the cap of 15 on `CLAUDE_CODE_MAX_RETRIES`
+ * `claude agents` session rows now show pull-request links as bare `#N` without the redundant “PR” label
+
+
+
2.1.198
July 1, 2026
+ * Subagents now run in the background by default, so Claude keeps working while they run and is notified when they finish (previously a gradual rollout)
* Claude in Chrome is now generally available
* Added background agent notifications in `claude agents` — sessions that need input or finish now fire the `Notification` hook (`agent_needs_input` / `agent_completed`)
* Added `/dataviz` skill for chart and dashboard design guidance with a runnable color-palette validator
--- a/chrome.md
+++ b/chrome.md
@@ -1,6 +1,6 @@
Claude Code integrates with the [Claude in Chrome browser extension](<https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn>) to give you browser automation capabilities from the CLI or the [VS Code extension](</docs/en/vs-code#automate-browser-tasks-with-chrome>). Build your code, then test and debug in the browser without switching contexts. Claude opens new tabs for browser tasks and shares your browser’s login state, so it can access any site you’re already signed into. Browser actions run in a visible Chrome window in real time. When Claude encounters a login page or CAPTCHA, it pauses and asks you to handle it manually.
-Chrome integration is in beta and currently works with Google Chrome and Microsoft Edge. It is not yet supported on Brave, Arc, or other Chromium-based browsers. WSL (Windows Subsystem for Linux) is also not supported.
+Chrome integration works with Google Chrome and Microsoft Edge. It isn’t yet supported on Brave, Arc, or other Chromium-based browsers. It also isn’t supported in Windows Subsystem for Linux (WSL).
##
@@ -78,6 +78,19 @@
Site-level permissions are inherited from the Chrome extension. Manage permissions in the Chrome extension settings to control which sites Claude can browse, click, and type on.
+###
+
+
+
+Browser tools in plan mode
+
+In [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>), browser tool calls that only read the page or browser state run without a permission prompt, and calls that change state prompt for approval.
+
+ * **Read-only calls** : `read_page`, `get_page_text`, `find`, reading console messages or network requests, and taking a screenshot
+ * **State-changing calls** : clicks, typing, navigation, tab and window management, and recording a GIF
+
+As of v2.1.199, an otherwise read-only call that sets a state-changing input flag, such as `createIfEmpty` on `tabs_context_mcp`, `clear` on the console and network readers, or `save_to_disk` on a screenshot, also prompts for approval. A `browser_batch` call runs without a prompt only when every action inside it is read-only.
+
##
@@ -200,7 +213,7 @@
4. Run `/chrome` and select “Reconnect extension” to re-establish the connection
5. If the issue persists, restart both Claude Code and Chrome
-The first time you enable Chrome integration, Claude Code installs a native messaging host configuration file. Chrome reads this file on startup, so if the extension isn’t detected on your first attempt, restart Chrome to pick up the new configuration. If the connection still fails, verify the host configuration file exists at: For Chrome:
+The first time you enable Chrome integration, Claude Code installs a native messaging host configuration file. Chrome reads this file on startup, so if the extension isn’t detected on your first attempt, restart Chrome to pick up the new configuration. As of v2.1.199, Claude Code opens a browser tab prompting you to connect the extension only on that first install. Later sessions that rewrite the configuration file, for example after switching Claude Code builds or config directories, don’t reopen it. If the connection still fails, verify the host configuration file exists at: For Chrome:
* **macOS** : `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`
* **Linux** : `~/.config/google-chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`
modified
Claude apps gateway for Amazon Bedrock, Claude Platform on AWS, Google Cloud, and Microsoft Foundry
View current →
--- a/claude-apps-gateway.md
+++ b/claude-apps-gateway.md
@@ -1,4 +1,4 @@
-The Claude apps gateway is designed for organizations that must — or prefer to — route inference through their own cloud provider, for example to meet [data residency](</docs/en/claude-apps-gateway-deploy#compliance-posture>) requirements. If you don’t have this requirement, and want access to other features such as SCIM provisioning or Claude Code on web & mobile, Claude Enterprise may be a better fit. See the [feature availability](</docs/en/feature-availability>) page for a full comparison of all deployment methods.
+The Claude apps gateway is designed for organizations that must, or prefer to, route inference through their own cloud provider, for example to meet [data residency](</docs/en/claude-apps-gateway-deploy#compliance-posture>) requirements. If you don’t have this requirement, and want access to other features such as SCIM provisioning or Claude Code on web and mobile, Claude Enterprise may be a better fit. See the [feature availability](</docs/en/feature-availability>) page for a full comparison of all deployment methods.
Claude apps gateway is a self-hosted service that sits between your developers’ Claude Code clients and your model provider. Developers sign in with your corporate identity provider (IdP) instead of holding API keys or cloud credentials. The gateway holds the upstream credential, enforces model access and [managed settings](</docs/en/permissions#managed-settings>) by IdP group, and relays usage telemetry to your own observability stack. It is included in the `claude` binary, so the same executable that runs Claude Code on a laptop runs the gateway server with `claude gateway --config gateway.yaml`. This page covers:
@@ -21,7 +21,7 @@
* **Access control** : your IdP groups map to model allowlists and [managed settings](</docs/en/permissions#managed-settings>) policies. The gateway enforces model access server-side, rejecting requests for non-granted models, and selects each group’s managed settings policy, which the CLI applies at the [managed settings tier](</docs/en/settings#settings-precedence>). Different teams get different models, tools, and permissions, and a developer can’t override what their policy locks.
* **Settings delivery** : the gateway delivers managed settings to signed-in clients itself, taking the place of [server-managed settings](</docs/en/server-managed-settings>) from the claude.ai admin console.
* **Telemetry** : each configured destination, such as Datadog, Splunk, or ClickHouse, receives [OpenTelemetry Protocol (OTLP) metrics](</docs/en/monitoring-usage>) with token counts, model, user identity, and latency by default, with logs and traces as per-destination opt-ins.
- * **Upstream routing** : clients speak the Anthropic Messages API to the gateway, and the gateway translates for each upstream, whether Bedrock, Google Cloud’s Agent Platform, Foundry, or the Anthropic API, with failover between them. You can change regions, providers, or failover order without developers noticing or reconfiguring.
+ * **Upstream routing** : clients speak the Anthropic Messages API to the gateway, and the gateway translates for each upstream, whether Bedrock, [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), Google Cloud’s Agent Platform, Foundry, or the Anthropic API, with failover between them. You can change regions, providers, or failover order without developers noticing or reconfiguring.
The gateway’s own data plane sends nothing to Anthropic infrastructure unless the Anthropic API is a configured upstream. You control where telemetry, audit logs, managed settings, and your developers’ IdP identity go, and the gateway sends none of them to Anthropic. For the remaining traffic the CLI process can send and how to close it, see [Compliance posture](</docs/en/claude-apps-gateway-deploy#compliance-posture>).
@@ -41,7 +41,7 @@
Quickstart
-This quickstart walks the minimal path: register an OAuth client in your IdP, write a `gateway.yaml`, run the gateway alongside Postgres with Docker Compose, and verify sign-in end to end. It uses an Amazon Bedrock upstream; Google Cloud’s Agent Platform, Foundry, and the Anthropic API are equally supported by swapping the `upstreams` block as shown in the [configuration reference](</docs/en/claude-apps-gateway-config#upstreams>). At the end you have a gateway a developer can `/login` to.
+This quickstart walks the minimal path: register an OAuth client in your IdP, write a `gateway.yaml`, run the gateway alongside Postgres with Docker Compose, and verify sign-in end to end. It uses an Amazon Bedrock upstream; Claude Platform on AWS, Google Cloud’s Agent Platform, Foundry, and the Anthropic API are equally supported by swapping the `upstreams` block as shown in the [configuration reference](</docs/en/claude-apps-gateway-config#upstreams>). At the end you have a gateway a developer can `/login` to.
**Deploy on your private network.** Claude Code only connects to a gateway whose address is private. This is a security guard, because a trusted gateway can push settings that run commands on developer machines. Put the gateway behind an internal load balancer or VPN and give it a hostname that resolves to private IPs only.
@@ -55,13 +55,13 @@
You need| Details
---|---
-Claude Code v2.1.195 or later| The `claude gateway` subcommand and the gateway sign-in flow ship in v2.1.195. Earlier public builds don’t include them. Both the machine running the gateway server and each developer’s machine must be on v2.1.195 or later; run `claude update` to get the latest release.
-OpenID Connect (OIDC) identity provider| Okta, Microsoft Entra ID, Google Workspace, Keycloak, or Dex, or any other OIDC-compliant IdP such as PingFederate. The gateway runs standard OIDC discovery and the authorization-code flow against it. SAML and LDAP are not supported.
+Claude Code v2.1.195 or later| The `claude gateway` subcommand and the gateway sign-in flow ship in v2.1.195. Earlier public builds don’t include them. Both the machine running the gateway server and each developer’s machine must be on v2.1.195 or later; run `claude update` to get the latest release. The [Claude Platform on AWS upstream](</docs/en/claude-apps-gateway-config#claude-platform-on-aws>) requires Claude Code v2.1.198 or later on the gateway server.
+OpenID Connect (OIDC) identity provider| Okta, Microsoft Entra ID, Google Workspace, Keycloak, or Dex, or any other OIDC-compliant IdP such as PingFederate. The gateway runs standard OIDC discovery and the authorization-code flow against it. SAML and LDAP aren’t supported.
PostgreSQL 14 or later| Backs the device sign-in flow, where the browser callback writes and the polling CLI reads, plus rate-limit counters. Any managed Postgres works, including the smallest tier. Without spend limits configured, the gateway stores a few KB of short-lived auth state; with [spend limits](</docs/en/claude-apps-gateway-spend-limits>), it also holds durable spend, audit, and identity tables that should be backed up. TLS via `?sslmode=require` is recommended.
-Model upstream| Amazon Bedrock credentials, Google Cloud credentials, a Microsoft Foundry resource, or an Anthropic API key. Multiple upstreams are supported with failover.
+Model upstream| Amazon Bedrock credentials, Claude Platform on AWS credentials, Google Cloud credentials, a Microsoft Foundry resource, or an Anthropic API key. Multiple upstreams are supported with failover.
HTTPS| The gateway must be reachable over `https://` from developer laptops and from any browser used for sign-in; the gateway serves the device-verification page on the same listener. Either provide a TLS cert via `listen.tls`, or run behind a TLS-terminating ingress and set `listen.public_url`. A plain `http://` origin is accepted only on loopback, for local development.
Private-network address| At `/login`, Claude Code requires the gateway’s hostname or IP address to resolve only to private addresses: RFC 1918, CGNAT `100.64.0.0/10`, IPv6 ULA `fc00::/7`, or loopback for local development. The check runs on each resolved IP, so if any address the name resolves to is public, `/login` rejects the URL. If developer machines route HTTPS through a corporate proxy, sign-in also requires the proxy host to resolve to private addresses; if it doesn’t, add the gateway host to `NO_PROXY` so the CLI connects directly.
-Linux runtime| The gateway server runs only on the native Linux binary. macOS works for local development. Windows is not supported as a server platform.
+Linux runtime| The gateway server runs only on the native Linux binary. macOS works for local development. Windows isn’t supported as a server platform.
The gateway server requires the native `claude` binary; download a pinned release as described in [Install Claude Code](</docs/en/setup>). The server uses runtime features that aren’t available when Claude Code runs under Node. If you see `requires the native binary` at boot, switch to one of the standalone install methods.
@@ -282,7 +282,7 @@
Feature| Status| Notes
---|---|---
-Inference forwarding (Bedrock, Agent Platform, Foundry, Anthropic)| Available| With per-upstream model translation and failover. The Bedrock upstream uses the `bedrock-runtime` endpoint and the AWS default credential chain; the Bedrock [Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>) is not a supported upstream.
+Inference forwarding (Bedrock, Claude Platform on AWS, Agent Platform, Foundry, Anthropic)| Available| With per-upstream model translation and failover. The Bedrock upstream uses the `bedrock-runtime` endpoint and the AWS default credential chain; the Bedrock [Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>) is not a supported upstream. The [Claude Platform on AWS upstream](</docs/en/claude-apps-gateway-config#claude-platform-on-aws>) requires Claude Code v2.1.198 or later on the gateway server.
Model access and managed settings by IdP group| Available| Model access is enforced server-side; managed settings are delivered per IdP group and applied by the CLI at the [managed settings tier](</docs/en/settings#settings-precedence>)
Telemetry fan-out (OTLP/HTTP)| Available| Identity-stamped per export; both protobuf and JSON encodings
OIDC identity providers| Available| Any OIDC-compliant IdP; the gateway runs standard OIDC discovery and the authorization-code flow. See [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) for per-IdP configuration
Show diff (124 lines)
--- a/claude-apps-gateway-config.md
+++ b/claude-apps-gateway-config.md
@@ -1,4 +1,4 @@
-A Claude apps gateway deployment is configured by one YAML file, conventionally `gateway.yaml`. The file defines everything the gateway does: where it listens, how developers sign in, where inference goes, and which policies and telemetry apply. This page is the reference for every option in that file. To write your first one, start from the [quickstart](</docs/en/claude-apps-gateway#quickstart>), which builds a minimal working config and runs it; once you have a config you’re happy with, the [deployment guide](</docs/en/claude-apps-gateway-deploy>) covers containerizing and hosting it on Kubernetes, Cloud Run, or your own platform. The gateway reads the file once, at startup, with `claude gateway --config /path/to/gateway.yaml`. Every option is validated against a schema at boot, so a malformed config fails at start with a field-level error rather than at first use. The complete example at the end of this page exercises every section.
+A Claude apps gateway deployment is configured by one YAML file, conventionally `gateway.yaml`. The file defines everything the gateway does: where it listens, how developers sign in, where inference goes, and which policies and telemetry apply. This page is the reference for every option in that file. To write your first one, start from the [quickstart](</docs/en/claude-apps-gateway#quickstart>), which builds a minimal working config and runs it. Once you have a config you’re happy with, the [deployment guide](</docs/en/claude-apps-gateway-deploy>) covers containerizing and hosting it on Kubernetes, Cloud Run, or your own platform. The gateway reads the file once, at startup, with `claude gateway --config /path/to/gateway.yaml`. Every option is validated against a schema at boot, so a malformed config fails at start with a field-level error rather than at first use. The complete example at the end of this page exercises every section.
##
@@ -12,7 +12,7 @@
* `oidc`: your identity provider (IdP), including issuer, client, claim mapping, and who may sign in
* `session`: the bearer tokens the gateway mints, with secret and lifetime
* `store`: PostgreSQL, for device grants and rate-limit counters
- * `upstreams`: where inference goes, whether Anthropic, Bedrock, Agent Platform, or Foundry
+ * `upstreams`: where inference goes, whether Anthropic, Bedrock, Claude Platform on AWS, Agent Platform, or Foundry
**Optional sections:**
@@ -64,7 +64,7 @@
`oidc`
-OpenID Connect (OIDC) is the SSO protocol the gateway uses with your identity provider; see [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) for what to register on the IdP side. The `oidc` block connects the gateway to your identity provider and decides who can sign in. It names the issuer and OAuth client, maps the claims that carry email and groups, and restricts sign-in by email domain or group.
+The `oidc` block connects the gateway to your identity provider and decides who can sign in. It names the issuer and OAuth client, maps the claims that carry email and groups, and restricts sign-in by email domain or group. OpenID Connect (OIDC) is the SSO protocol the gateway uses with your identity provider; see [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) for what to register on the IdP side.
Field| Required| Description
---|---|---
@@ -123,7 +123,7 @@
`upstreams`
-`upstreams` is an ordered list. The gateway forwards inference to the first upstream that resolves the requested model. On `5xx`, `429`, or timeout it fails over to the next; other `4xx` doesn’t, because those errors are attributable to the request rather than the upstream. Multiple upstreams of the same provider must set a distinct `name:`. Bedrock, Agent Platform, and Foundry clients are built once at startup, and their SDKs refresh credentials internally, so rotating cloud credentials doesn’t require a restart. Static Anthropic API keys and bearers are read at startup; see Anthropic API.
+`upstreams` is an ordered list. The gateway forwards inference to the first upstream that resolves the requested model. On `5xx`, `429`, `401`, `403`, `404`, or timeout it fails over to the next; other `4xx` doesn’t, because those errors are attributable to the request rather than the upstream. A `401` or `403` means the gateway’s own credential failed against that upstream, and a `404` means that upstream doesn’t serve the requested model, so a later upstream in the list still can. Failover on `404` requires gateway v2.1.198 or later. Earlier releases returned the first `404` to the client even when a later upstream in the list served the model. Multiple upstreams of the same provider must set a distinct `name:`. Bedrock, Claude Platform on AWS, Agent Platform, and Foundry clients are built once at startup, and their SDKs refresh credentials internally, so rotating cloud credentials doesn’t require a restart. Static Anthropic API keys and bearers are read at startup; see Anthropic API.
####
@@ -195,6 +195,41 @@
+Claude Platform on AWS
+
+Claude Platform on AWS serves the first-party Anthropic API on AWS infrastructure at `aws-external-anthropic.<region>.api.aws`. It uses first-party model IDs, honors `anthropic-beta` headers as sent, and serves `count_tokens`, so none of the Bedrock-specific translation applies. The `anthropicAws` provider requires Claude Code v2.1.198 or later; earlier gateway releases reject it at boot. For the client-side deployment of the same platform, see [Claude Code on Claude Platform on AWS](</docs/en/claude-platform-on-aws>). The gateway-side upstream:
+
+ upstreams:
+ - provider: anthropicAws
+ region: us-east-1
+ workspace_id: wrkspc_...
+ auth:
+ api_key: ${ANTHROPIC_AWS_API_KEY} # sent as x-api-key
+ # OR SigV4 via the AWS default credential chain:
+ # auth: {}
+ # OR explicit SigV4 credentials:
+ # auth:
+ # aws_access_key_id: ${AWS_ACCESS_KEY_ID}
+ # aws_secret_access_key: ${AWS_SECRET_ACCESS_KEY}
+ # Override the derived endpoint:
+ # base_url: https://aws-external-anthropic.us-east-1.api.aws
+
+The platform runs in a separate AWS account from Amazon Bedrock and signs SigV4 requests for its own service name, `aws-external-anthropic`, so a Bedrock-scoped IAM role doesn’t authorize it. An API key in `auth.api_key` takes precedence when SigV4 credentials are also set. An empty `auth` block uses the AWS SDK’s default credential chain, the same chain the Amazon Bedrock upstream uses.
+
+Field| Required| Description
+---|---|---
+`region`| Yes| AWS region, lowercase letters, digits, and hyphens. The gateway derives the endpoint from it as `https://aws-external-anthropic.<region>.api.aws`.
+`workspace_id`| Yes| Sent as a header on every request; the platform requires it
+`auth.api_key`| No| API key for the platform, sent as `x-api-key`. Not a bearer token: the two auth modes are an API key or SigV4.
+`auth.aws_access_key_id` / `auth.aws_secret_access_key`| No| Explicit SigV4 credentials. Setting one without the other fails at boot. `auth.aws_session_token` is accepted alongside them.
+`base_url`| No| Override the derived endpoint
+
+Because the platform resolves first-party model IDs, the built-in catalog routes to it with no `models:` block. When you curate a `models:` list, key the entry `anthropicAws:` with the first-party ID.
+
+####
+
+
+
Google Cloud Agent Platform
For the equivalent client-side setup, see [Claude Code on Google Cloud](</docs/en/google-vertex-ai>). The gateway-side upstream:
@@ -251,7 +286,7 @@
Multiple upstreams
-The same provider can appear more than once with a distinct `name:`. This covers different regions, different accounts via different credential chains, provisioned throughput versus on-demand, and cross-provider fallback. The gateway tries upstreams in order. `5xx`, `429`, timeouts, and missing-endpoint (`501`) fail over; other `4xx` doesn’t. `429` is per-upstream capacity, so provisioned-throughput (PT) exhaustion fails over to on-demand. An upstream that can’t resolve the requested model is skipped without a network round-trip. This example routes a provisioned-throughput Bedrock allotment first, overflows to on-demand and a second account, and falls back to the Anthropic API last:
+The same provider can appear more than once with a distinct `name:`. This covers different regions, different accounts via different credential chains, provisioned throughput versus on-demand, and cross-provider fallback. The gateway tries upstreams in order. `5xx`, `429`, `401`, `403`, `404`, timeouts, and missing-endpoint (`501`) fail over; other `4xx` doesn’t. `429` is per-upstream capacity, so provisioned-throughput (PT) exhaustion fails over to on-demand. `404` is per-upstream model availability, so an upstream that hasn’t enabled a model doesn’t block a later upstream that serves it. An upstream that can’t resolve the requested model is skipped without a network round-trip. This example routes a provisioned-throughput Bedrock allotment first, overflows to on-demand and a second account, and falls back to the Anthropic API last:
upstreams:
# Primary: provisioned throughput in your home region.
@@ -491,6 +526,7 @@
* `sandbox.network.allowManagedDomainsOnly` and `sandbox.filesystem.allowManagedReadPathsOnly`: when locked, the corresponding allowlists are unioned across sources
* [`allowAllClaudeAiMcps`](</docs/en/settings#available-settings>): allow-only override for the claude.ai MCP server allowlist
* `sandbox.bwrapPath` and `sandbox.socatPath`: filesystem paths to the [sandbox](</docs/en/sandboxing>) helper binaries
+ * [`forceRemoteSettingsRefresh`](</docs/en/server-managed-settings>): blocks startup until remote managed settings are freshly fetched, so an MDM or file policy that sets it is honored even when a cached remote payload that lacks the key is the highest-priority source
Every other key, including `allowManagedPermissionRulesOnly` and `disableBypassPermissionsMode`, comes from the highest-priority source only. See [Settings precedence](</docs/en/settings#settings-precedence>) for the same rule on the settings page. Gateway policies apply to every Claude Code invocation on the machine, including non-interactive `claude -p` runs and sessions spawned by the Agent SDK. If the gateway is unreachable at startup, signed-in sessions exit with an error rather than running without their policy.
@@ -548,7 +584,7 @@
`limits`| `max_request_bytes`| 32 MiB| Max inbound request body; oversize requests get `413` before the body is buffered. Raise for large file or image requests.
`limits`| `max_request_header_bytes`| unset| When set, oversize headers return `431`
`limits`| `max_url_length`| unset| When set, an over-long URL returns `414`
-`timeouts`| `upstream_ttfb_ms`| 120000| Max wait for the upstream’s response headers (time to first byte). The response body then streams with no wall-clock cap. Applies to the direct Anthropic upstream path; Bedrock, Agent Platform, and Foundry are bounded by their provider SDK’s own timeout.
+`timeouts`| `upstream_ttfb_ms`| 120000| Max wait for the upstream’s response headers (time to first byte). The response body then streams with no wall-clock cap. Applies to the direct Anthropic upstream path; every other provider is bounded by its provider SDK’s own timeout.
`rate_limits`| `device_authorization.max` / `.window_seconds`| 30 / 600| Per-IP rate limit on the unauthenticated device-authorization endpoint. Raise for a large org behind a shared egress IP or NAT. These limits apply only to the device-grant sign-in flow, not to `/v1/messages` inference. See [User-code brute-force resistance](</docs/en/claude-apps-gateway-deploy#user-code-brute-force-resistance>).
`rate_limits`| `device_verify.max` / `.window_seconds`| 10 / 600| Per-IP rate limit on `user_code` submissions at `/device`
@@ -633,6 +669,12 @@
# region: us-east-1
# auth: {}
+ # - provider: anthropicAws
+ # region: us-east-1
+ # workspace_id: wrkspc_...
+ # auth:
+ # api_key: ${ANTHROPIC_AWS_API_KEY}
+
# - provider: vertex
# region: us-east5
# project_id: example-prod
@@ -649,6 +691,7 @@
upstream_model:
anthropic: claude-opus-4-8
# bedrock: us.anthropic.claude-opus-4-8
+ # anthropicAws: claude-opus-4-8
# vertex: claude-opus-4-8
# foundry: <your-opus-deployment-name>
- id: claude-sonnet-4-6
--- a/claude-apps-gateway-deploy.md
+++ b/claude-apps-gateway-deploy.md
@@ -76,7 +76,7 @@
* Terminate TLS at the Ingress and set `listen.public_url` to the Ingress hostname
* Point the readiness probe at `GET /readyz` and the liveness probe at `GET /healthz`
-**Workload identity** Prefer the platform’s workload identity over static keys: IRSA on EKS for Bedrock, Workload Identity on GKE for Agent Platform, and workload identity on AKS for Foundry. Set `auth: {}` in the upstream block, or `use_azure_ad: true` for Foundry, and the gateway picks up the pod’s identity through that provider’s default credential chain. For a cross-cloud pairing, such as a Bedrock upstream on GKE, set explicit credentials in the upstream’s `auth` block instead. The [`upstreams` reference](</docs/en/claude-apps-gateway-config#upstreams>) has per-platform setup details.
+**Workload identity** Prefer the platform’s workload identity over static keys: IRSA on EKS for Bedrock and for Claude Platform on AWS, Workload Identity on GKE for Agent Platform, and workload identity on AKS for Foundry. Set `auth: {}` in the upstream block, or `use_azure_ad: true` for Foundry, and the gateway picks up the pod’s identity through that provider’s default credential chain. For a cross-cloud pairing, such as a Bedrock upstream on GKE, set explicit credentials in the upstream’s `auth` block instead. The [`upstreams` reference](</docs/en/claude-apps-gateway-config#upstreams>) has per-platform setup details.
###
--- a/claude-code-features.md
+++ b/claude-code-features.md
@@ -53,7 +53,7 @@
---|---|---
Managed policy settings| Endpoint-managed policy, such as an MDM plist, registry policy, or managed settings file, loads from the host. [Server-managed settings](</docs/en/server-managed-settings>) are fetched on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>) when the session authenticates with an organization OAuth login or a directly configured API key| Endpoint policy: remove the managed settings file, plist, or registry policy from the host. Server-managed settings: controlled by your org admin; cannot be disabled from the SDK
`~/.claude.json` global config| Always read| Relocate with `CLAUDE_CONFIG_DIR` in `env`
-Auto memory at `~/.claude/projects/<project>/memory/`| Loaded by default into the system prompt| Set `autoMemoryEnabled: false` in settings, or `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`
+Auto memory at `~/.claude/projects/<project>/memory/`| Loaded into the system prompt at session start. The agent writes new memories there with the standard `Write` and `Edit` tools rather than a dedicated memory tool, so those tools must be enabled for the agent to save memories| Set `autoMemoryEnabled: false` in settings, or `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`
[claude.ai MCP connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>)| Loaded when the active authentication method is a claude.ai subscription. Passing `mcpServers: {}` does not suppress them| Set `strictMcpConfig: true`, [`disableClaudeAiConnectors: true`](</docs/en/mcp#disable-claude-ai-connectors>) in settings, or `ENABLE_CLAUDEAI_MCP_SERVERS=false` in `env`
Do not rely on default `query()` options for multi-tenant isolation. Because the inputs above are read regardless of `settingSources`, an SDK process can pick up host-level configuration and per-directory memory. For multi-tenant deployments, run each tenant in its own filesystem and set `settingSources: []` plus `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Server-managed settings](</docs/en/server-managed-settings>) are fetched when the process authenticates with an organization credential; filesystem isolation does not remove them. See [Secure deployment](</docs/en/agent-sdk/secure-deployment>).
--- a/claude-code-on-the-web.md
+++ b/claude-code-on-the-web.md
@@ -675,7 +675,7 @@
Requirement| Details
---|---
Clean git state| Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed.
-Correct repository| You must run `--teleport` from a checkout of the same repository, not a fork.
+Correct repository| You must run `--teleport` from a checkout of the same repository, not a fork. As of v2.1.199, Claude Code accepts a checkout even when it can’t parse the remote into a hostname, such as an SSH host alias like `git@work:owner/repo.git` or an `insteadOf`-rewritten short form. It shows a confirmation prompt first, and only when the remote’s owner and repository name match the session’s repository.
Branch available| The branch from the cloud session must have been pushed to the remote. Teleport automatically fetches and checks it out.
Same account| You must be authenticated to the same claude.ai account used in the cloud session.
--- a/claude-platform-on-aws.md
+++ b/claude-platform-on-aws.md
@@ -32,7 +32,7 @@
aws sso login --profile my-profile
export AWS_PROFILE=my-profile
-For CI and automation, give the runner an IAM role with permission to invoke the Anthropic service and set `AWS_REGION`. The credential chain picks the role up automatically. If your SSO credentials expire mid-session, configure [`awsAuthRefresh`](</docs/en/amazon-bedrock#advanced-credential-configuration>) so Claude Code re-runs your login command and retries instead of failing. Add the command to your `settings.json`:
+For CI and automation, give the runner an IAM role with permission to invoke the Anthropic service and set `AWS_REGION`. The credential chain picks the role up automatically. If your SSO credentials expire mid-session, configure [`awsAuthRefresh`](</docs/en/amazon-bedrock#advanced-credential-configuration>) so Claude Code re-runs your login command and retries instead of failing. Automatic refresh on Claude Platform on AWS requires Claude Code v2.1.198 or later; earlier versions stop with a prompt to run `/login`, which can’t refresh AWS credentials. Add the command to your `settings.json`:
{
"awsAuthRefresh": "aws sso login --profile my-profile"
--- a/cli-reference.md
+++ b/cli-reference.md
@@ -39,7 +39,7 @@
`claude stop <id>`| Stop a [background session](</docs/en/agent-view#manage-sessions-from-the-shell>). Also accepts `claude kill`| `claude stop 7c5dcf5d`
`claude ultrareview [target]`| Run [ultrareview](</docs/en/ultrareview#run-ultrareview-non-interactively>) non-interactively. Prints findings to stdout and exits 0 on success or 1 on failure. Use `--json` for the raw payload and `--timeout <minutes>` to override the 30-minute default| `claude ultrareview 1234 --json`
-If you mistype a subcommand, Claude Code suggests the closest match and exits without starting a session. For example, `claude udpate` prints `Did you mean claude update?`.
+If you mistype a subcommand, Claude Code suggests the closest match and exits without starting a session. For example, `claude udpate` prints `Did you mean claude update?`. As of v2.1.199, `claude --dangerously-skip-permissions daemon <subcommand>` runs the `daemon` subcommand. Earlier versions treated `daemon <subcommand>` as the prompt for a new interactive session, so the subcommand never ran when the flag came first, a common setup when `claude` is aliased to include the flag. Only a leading `--dangerously-skip-permissions` or `--allow-dangerously-skip-permissions` routes to `daemon` this way; any other leading flag still starts an interactive session.
##
@@ -62,7 +62,7 @@
`--ax-screen-reader`| Render screen-reader friendly output: flat text without decorative borders or animations. Forces the classic renderer, so the [`tui`](</docs/en/settings#available-settings>) setting has no effect for the session. Takes precedence over [`CLAUDE_AX_SCREEN_READER`](</docs/en/env-vars>) and the [`axScreenReader`](</docs/en/settings#available-settings>) setting. Requires Claude Code v2.1.181 or later| `claude --ax-screen-reader`
`--bare`| Minimal mode: skip auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md so scripted calls start faster. Claude has access to Bash, file read, and file edit tools. Sets [`CLAUDE_CODE_SIMPLE`](</docs/en/env-vars>). See [bare mode](</docs/en/headless#start-faster-with-bare-mode>)| `claude --bare -p "query"`
`--betas`| Beta headers to include in API requests (API key users only)| `claude --betas interleaved-thinking`
-`--bg`, `--background`| Start the session as a [background agent](</docs/en/agent-view>) and return immediately. Prints the session ID and management commands. Combine with `--exec` to run a shell command as a background job instead of a Claude session, or with `--agent` to run a specific subagent| `claude --bg "investigate the flaky test"`
+`--bg`, `--background`| Start the session as a [background agent](</docs/en/agent-view>) and return immediately. Prints the session ID and management commands. Combine with `--exec` to run a shell command as a background job instead of a Claude session, or with `--agent` to run a specific subagent. Cannot be combined with `-p`/`--print`; see the [error reference](</docs/en/errors#command-line-errors>)| `claude --bg "investigate the flaky test"`
`--channels`| (Research preview) MCP servers whose [channel](</docs/en/channels>) notifications Claude should listen for in this session. Space-separated list of `plugin:<name>@<marketplace>` entries. Requires Claude.ai authentication| `claude --channels plugin:my-notifier@my-marketplace`
`--chrome`| Enable [Chrome browser integration](</docs/en/chrome>) for web automation and testing| `claude --chrome`
`--continue`, `-c`| Load the most recent conversation in the current directory. Includes sessions that added this directory with `/add-dir`| `claude --continue`
@@ -98,7 +98,7 @@
`--no-session-persistence`| Disable session persistence so sessions are not saved to disk and cannot be resumed. Print mode only. The [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>) environment variable does the same in any mode| `claude -p --no-session-persistence "query"`
`--output-format`| Specify output format for print mode (options: `text`, `json`, `stream-json`)| `claude -p "query" --output-format json`
`--permission-mode`| Begin in a specified [permission mode](</docs/en/permission-modes>). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, or `bypassPermissions`. Overrides `defaultMode` from settings files| `claude --permission-mode plan`
-`--permission-prompt-tool`| Specify an MCP tool to handle permission prompts in non-interactive mode| `claude -p --permission-prompt-tool mcp_auth_tool "query"`
+`--permission-prompt-tool`| Specify an MCP tool to handle permission prompts in non-interactive mode. As of v2.1.199, the prompt tool can’t approve an MCP tool marked as [requiring user interaction](</docs/en/mcp#require-approval-for-a-specific-tool>): an `allow` result for one is converted to a deny| `claude -p --permission-prompt-tool mcp_auth_tool "query"`
`--plugin-dir`| Load a plugin from a directory or `.zip` archive for this session only. Each flag takes one path. Repeat the flag for multiple plugins: `--plugin-dir A --plugin-dir B.zip`| `claude --plugin-dir ./my-plugin`
`--plugin-url`| Fetch a plugin `.zip` archive from a URL for this session only. Repeat the flag for multiple plugins, or pass space-separated URLs in a single quoted value| `claude --plugin-url https://example.com/plugin.zip`
`--print`, `-p`| Print response without interactive mode (see [Agent SDK documentation](</docs/en/agent-sdk/overview>) for programmatic usage details)| `claude -p "query"`
--- a/commands.md
+++ b/commands.md
@@ -1,4 +1,4 @@
-Commands control Claude Code from inside a session. They provide a quick way to switch models, manage permissions, clear context, run a workflow, and more. Type `/` to see every command available to you, or type `/` followed by letters to filter. A command is only recognized at the start of your message. Text that follows the command name is passed to it as arguments.
+Commands control Claude Code from inside a session. They provide a quick way to switch models, manage permissions, clear context, run a workflow, and more. Type `/` to see every command available to you, or type `/` followed by letters to filter. A command is only recognized at the start of your message. Text that follows the command name becomes its arguments. As of v2.1.199, [skills](</docs/en/skills#pass-arguments-to-skills>) are the exception: a skill invocation followed by more skills, such as `/skill-a /skill-b do XYZ`, loads every skill named at the start and passes the trailing text to each as arguments. Up to six skills can be chained.
##
@@ -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` and `/agents` to set up any servers or subagents the project needs, and `/permissions` to set the approval rules you want. **During a task.** `/plan` switches into plan mode before a large change. `/model` and `/effort` adjust how much reasoning you’re spending. When the conversation gets long, `/context` shows where the window is going and `/compact` summarizes it down; use `/btw` for a quick aside that shouldn’t bloat history. **Running work in parallel.** `/agents` opens the manager for the [subagents](</docs/en/sub-agents>) Claude can delegate side tasks to, 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` runs the same read-only review on a GitHub pull request, and `/security-review` gives a deeper read-only pass. `/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` runs the same read-only review on a GitHub pull request, and `/security-review` gives a deeper read-only pass. `/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.
##
@@ -27,7 +27,7 @@
---|---
`/add-dir <path>`| Add a working directory for file access during the current session. Most `.claude/` configuration is [not discovered](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) from the added directory. You can later resume the session from the added directory with `--continue` or `--resume`
`/advisor [model|off]`| Enable or disable the [advisor tool](</docs/en/advisor>), which consults a second model for guidance at key moments during a task. Accepts `opus`, `sonnet`, `fable` (v2.1.170+), or a full model ID. Without an argument, opens a picker. Requires Claude Code v2.1.98 or later
-`/agents`| Manage [agent](</docs/en/sub-agents>) configurations
+`/agents`| As of v2.1.198, running `/agents` prints a reminder to ask Claude to create or manage [subagents](</docs/en/sub-agents>), or to edit `.claude/agents/` or `~/.claude/agents/` directly. On v2.1.197 and earlier, opens an interactive interface for creating and managing subagent configurations
`/autofix-pr [prompt]`| Spawn a [Claude Code on the web](</docs/en/claude-code-on-the-web#auto-fix-pull-requests>) session that watches the current branch’s PR and pushes fixes when CI fails or reviewers leave comments. Detects the open PR from your checked-out branch with `gh pr view`; to watch a different PR, check out its branch first. By default the cloud session is told to fix every CI failure and review comment; pass a prompt to give it different instructions, for example `/autofix-pr only fix lint and type errors`. Requires the `gh` CLI and access to [Claude Code on the web](</docs/en/claude-code-on-the-web>)
`/background [prompt]`| Detach the current session to run as a [background agent](</docs/en/agent-view>) and free this terminal. Pass a prompt to send one more instruction before detaching. Monitor the session with `claude agents`. Alias: `/bg`
`/batch <instruction>`| **[Skill](</docs/en/skills#bundled-skills>).** Orchestrate large-scale changes across a codebase in parallel. Researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once approved, spawns one [background subagent](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) per unit in an isolated [git worktree](</docs/en/worktrees>). Each subagent implements its unit, runs tests, and opens a pull request. Requires a git repository. Example: `/batch migrate src/ from Solid to React`
@@ -44,12 +44,13 @@
`/context [all]`| Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings. In [fullscreen mode](</docs/en/fullscreen>) the per-item breakdown is collapsed to keep the grid visible. Pass `all` to expand it
`/copy [N]`| Copy the last assistant response to clipboard. Pass a number `N` to copy the Nth-latest response: `/copy 2` copies the second-to-last. When code blocks are present, shows an interactive picker to select individual blocks or the full response. Press `w` in the picker to write the selection to a file instead of the clipboard, which is useful over SSH
`/cost`| Alias for `/usage`
+`/dataviz [request]`| **[Skill](</docs/en/skills#bundled-skills>).** Design guidance for charts, graphs, and dashboards. Claude picks the chart form for the data, assigns color by role, validates the palette for colorblind safety and contrast with a bundled script, and applies mark, interaction, and accessibility rules. Uses a brand-neutral placeholder palette that you replace with your own. Requires Claude Code v2.1.198 or later
`/debug [description]`| **[Skill](</docs/en/skills#bundled-skills>).** Enable debug logging for the current session and troubleshoot issues by reading the session debug log. Debug logging is off by default unless you started with `claude --debug`, so running `/debug` mid-session starts capturing logs from that point forward. Optionally describe the issue to focus the analysis
`/deep-research <question>`| **[Workflow](</docs/en/workflows#bundled-workflows>).** Fan out web searches on a question, fetch and cross-check sources, and synthesize a cited report
`/design-login`| Authorize design-system access for `/design-sync` with your claude.ai account
`/design-sync [hint]`| **[Skill](</docs/en/skills#bundled-skills>).** Convert your repo’s React design system and upload it to [Claude Design](<https://claude.ai/design>), so designs it produces use your real components. Optionally name the design system, for example `/design-sync Acme DS`. A first-time sync verifies every component and can take a few hours on a large repo. Available on the Anthropic API; on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry the underlying tool can’t reach claude.ai, so the command is unavailable
`/desktop`| Continue the current session in the Claude Code Desktop app. Requires macOS or Windows and a Claude subscription. Alias: `/app`
-`/diff`| Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files
+`/diff`| Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files. As of v2.1.198, the open viewer also refreshes automatically when the repository’s git state changes outside the session, such as a branch switch or commit in another terminal
`/doctor`| Diagnose and verify your Claude Code installation and settings. Results show with status icons. Press `f` to have Claude fix any reported issues
`/effort [level|auto]`| Set the model [effort level](</docs/en/model-config#adjust-effort-level>). Accepts `low`, `medium`, `high`, `xhigh`, `max`, or `ultracode`; available levels depend on the model, and `max` and `ultracode` are session-only. `ultracode` is a Claude Code setting that combines `xhigh` reasoning with automatic [workflow](</docs/en/workflows#let-claude-decide-with-ultracode>) orchestration. `auto` resets to the model default. Without an argument, opens an interactive slider; use left and right arrows to pick a level and `Enter` to apply. Takes effect immediately without waiting for the current response to finish
`/exit`| Exit the CLI. In an attached [background session](</docs/en/agent-view#attach-to-a-session>), this detaches and the session keeps running. Alias: `/quit`
@@ -57,7 +58,7 @@
`/fast [on|off]`| Toggle [fast mode](</docs/en/fast-mode>) on or off
`/feedback [report]`| Submit feedback, report a bug, or share your conversation. Aliases: `/bug`, `/share`
`/fewer-permission-prompts`| **[Skill](</docs/en/skills#bundled-skills>).** Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project `.claude/settings.json` to reduce permission prompts
-`/focus`| Toggle the focus view, which shows only your last prompt, a one-line tool-call summary with edit diffstats, and the final response. The selection persists across sessions; set [`viewMode`](</docs/en/settings#available-settings>) in settings to override it. Only available in [fullscreen rendering](</docs/en/fullscreen>)
+`/focus`| Toggle the focus view, which shows only your last prompt, a one-line tool-call summary with edit diffstats, and the final response. As of v2.1.198, the tool-call summary also counts the subagents launched in the turn and collapses completed background-task notifications into a single count. The selection persists across sessions; set [`viewMode`](</docs/en/settings#available-settings>) in settings to override it. Only available in [fullscreen rendering](</docs/en/fullscreen>)
`/fork <directive>`| Spawn a [forked subagent](</docs/en/sub-agents#fork-the-current-conversation>): a background subagent that inherits the full conversation and works on the directive while you keep going. Its result returns to your conversation when it finishes. To switch into a copy of the conversation yourself, use `/branch`. Before v2.1.161, `/fork` is an alias for `/branch`
`/goal [condition|clear]`| Set a [goal](</docs/en/goal>): Claude keeps working across turns until the condition is met. With no argument, shows the current or most recently achieved goal. `clear`, `stop`, `off`, `reset`, `none`, or `cancel` removes an active goal early
`/heapdump`| Write a JavaScript heap snapshot and a memory breakdown to `~/Desktop`, or your home directory on Linux without a Desktop folder, for diagnosing high memory usage. See [troubleshooting](</docs/en/troubleshooting#high-cpu-or-memory-usage>)
@@ -94,7 +95,7 @@
`/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, using the same review engine as `/code-review`. With no arguments, lists open PRs to pick from. 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 in the running app, not just in 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](</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
`/sandbox`| Toggle [sandbox mode](</docs/en/sandboxing>). Available on supported platforms only
`/schedule [description]`| Create, update, list, or run [routines](</docs/en/routines>), which execute on Anthropic-managed cloud infrastructure. Claude walks you through the setup conversationally. Alias: `/routines`
@@ -102,10 +103,10 @@
`/security-review`| Analyze pending changes on the current branch for security vulnerabilities. Reviews the git diff and identifies risks like injection, auth issues, and data exposure
`/setup-bedrock`| Configure [Amazon Bedrock](</docs/en/amazon-bedrock>) authentication, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_BEDROCK=1` is set. First-time Bedrock users can also access this wizard from the login screen
`/setup-vertex`| Configure [Google Vertex AI](</docs/en/google-vertex-ai>) authentication, project, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_VERTEX=1` is set. First-time Vertex AI users can also access this wizard from the login screen
-`/simplify [target]`| **[Skill](</docs/en/skills#bundled-skills>).** Review the changed code for cleanup opportunities and apply the fixes. Four review [agents](</docs/en/sub-agents>) run in parallel, covering reuse of existing helpers, simplification, efficiency, and whether the change sits at the right level of abstraction. From v2.1.154, the review does not look for correctness bugs. Use `/code-review` to find bugs. On earlier versions `/simplify` is equivalent to `/code-review --fix`. Pass a path or PR reference to review a specific target
-`/skills`| List available [skills](</docs/en/skills>). Press `t` to sort by token count. Press `Space` to [hide a skill from Claude or the `/` menu](</docs/en/skills#override-skill-visibility-from-settings>), then `Enter` to save
+`/simplify [target]`| **[Skill](</docs/en/skills#bundled-skills>).** Review the changed code for cleanup opportunities and apply the fixes. Four review [agents](</docs/en/sub-agents>) run in parallel, covering reuse of existing helpers, simplification, efficiency, and whether the change is at the right level of abstraction. From v2.1.154, the review doesn’t look for correctness bugs. Use `/code-review` to find bugs. On earlier versions, `/simplify` is equivalent to `/code-review --fix`. Pass a path or PR reference to review a specific target
+`/skills`| List available [skills](</docs/en/skills>). As of v2.1.121, type to filter the list by name. Press `t` to sort by token count. Press `Space` to [cycle a skill’s visibility to Claude and the `/` menu](</docs/en/skills#override-skill-visibility-from-settings>), then `Enter` to save
`/stats`| Alias for `/usage`. Opens on the Stats tab
-`/status`| Open the Settings interface (Status tab) showing version, model, account, and connectivity. Works while Claude is responding, without waiting for the current response to finish
+`/status`| Open the Settings interface on the Status tab, showing version, model, account, and connectivity. Works while Claude is responding
`/statusline`| Configure Claude Code’s [status line](</docs/en/statusline>). Describe what you want, or run without arguments to auto-configure from your shell prompt
`/stickers`| Order Claude Code stickers
`/stop`| Stop the current [background session](</docs/en/agent-view>). Only available while attached to a background session; the transcript and any worktree are kept. To detach without stopping, use `/exit` or press `←`
--- a/context-window.md
+++ b/context-window.md
@@ -19,7 +19,7 @@
What survives compaction
-When a long session compacts, Claude Code summarizes the conversation history to fit the context window. What happens to your instructions depends on how they were loaded:
+When a long session compacts, Claude Code summarizes the conversation history to fit the context window. As of v2.1.198, the summarization request inherits your session’s [extended thinking](</docs/en/model-config#extended-thinking>) configuration, so it reasons with thinking enabled when your session has it enabled and stays off otherwise. Thinking affects only how the summary is produced; your session settings are unchanged afterward. What happens to your instructions depends on how they were loaded:
Mechanism| After compaction
---|---
--- a/costs.md
+++ b/costs.md
@@ -89,7 +89,7 @@
* **Clear between tasks** : Use `/clear` to start fresh when switching to unrelated work. Stale context wastes tokens on every subsequent message. Use `/rename` before clearing so you can easily find the session later, then `/resume` to return to it.
* **Add custom compaction instructions** : `/compact Focus on code samples and API usage` tells Claude what to preserve during summarization.
-You can also customize compaction behavior in your CLAUDE.md:
+You can also customize compaction behavior in your CLAUDE.md file at the root of your project:
# Compact instructions
@@ -152,7 +152,7 @@
}
}
-The hook calls this script, which checks if the command is a test runner and modifies it to show only failures:
+The hook calls this script. Create the folder with `mkdir -p ~/.claude/hooks`, save the script below as `~/.claude/hooks/filter-test-output.sh`, and make it executable with `chmod +x ~/.claude/hooks/filter-test-output.sh`. It checks if the command is a test runner and modifies it to show only failures:
#!/bin/bash
input=$(cat)
@@ -180,7 +180,7 @@
Adjust extended thinking
-Extended thinking is enabled by default because it significantly improves performance on complex planning and reasoning tasks. Thinking tokens are billed as output tokens, and the default budget can be tens of thousands of tokens per request depending on the model. For simpler tasks where deep reasoning isn’t needed, you can reduce costs by lowering the [effort level](</docs/en/model-config#adjust-effort-level>) with `/effort` or in `/model`, disabling thinking in `/config`, or, on models with a [fixed thinking budget](</docs/en/model-config#adaptive-reasoning-and-fixed-thinking-budgets>), lowering the budget with `MAX_THINKING_TOKENS=8000`. Adaptive-reasoning models ignore nonzero budgets, so use effort levels there instead. Disabling thinking is not available on Fable 5, which always uses extended thinking.
+Extended thinking is enabled by default because it significantly improves performance on complex planning and reasoning tasks. Thinking tokens are billed as output tokens, and the default budget can be tens of thousands of tokens per request depending on the model. For simpler tasks where deep reasoning isn’t needed, you can reduce costs by lowering the [effort level](</docs/en/model-config#adjust-effort-level>) with `/effort` or in `/model`, disabling thinking in `/config`, or, on models with a [fixed thinking budget](</docs/en/model-config#adaptive-reasoning-and-fixed-thinking-budgets>), lowering the budget by setting the `MAX_THINKING_TOKENS` [environment variable](</docs/en/env-vars>), for example `MAX_THINKING_TOKENS=8000`. Adaptive-reasoning models ignore nonzero budgets, so use effort levels there instead. Disabling thinking is not available on Fable 5, which always uses extended thinking.
###
--- a/debug-your-config.md
+++ b/debug-your-config.md
@@ -6,13 +6,12 @@
See what loaded into context
-The `/context` command shows everything occupying the context window for the current session, broken down by category: system prompt, memory files, skills, MCP tools, and conversation messages. Run it first to confirm whether your `CLAUDE.md`, rules, or skill descriptions are present at all. For detail on a specific category, follow up with the dedicated command:
+The `/context` command shows everything occupying the context window for the current session, broken down by category: system prompt, memory files, skills, custom subagents with the source each loaded from, MCP tools, and conversation messages. Run it first to confirm whether your `CLAUDE.md`, rules, or skill descriptions are present at all. For detail on a specific category, follow up with the dedicated command:
Command| Shows
---|---
`/memory`| Which `CLAUDE.md` and rules files loaded, plus auto-memory entries
`/skills`| Available skills from project, user, and plugin sources
-`/agents`| Configured subagents and their settings
`/hooks`| Active hook configurations
`/mcp`| Connected MCP servers and their status
`/permissions`| Resolved allow and deny rules currently in effect
--- a/desktop.md
+++ b/desktop.md
@@ -799,7 +799,7 @@
* **Linux (beta)** : Computer Use isn’t yet available in the Linux desktop app. See [Claude Desktop on Linux](</docs/en/desktop-linux>).
* **Inline code suggestions** : Desktop does not provide autocomplete-style suggestions. It works through conversational prompts and explicit code changes.
* **Agent teams** : parallel Claude Code sessions that message each other are available in the [CLI](</docs/en/agent-teams>), not in Desktop. For multi-agent work inside one session, use [dynamic workflows](</docs/en/workflows>), which run in Desktop.
- * **Terminal-dialog commands** : built-in commands that open an interactive panel in the terminal, such as `/permissions`, `/config`, `/agents`, and `/doctor`, are not available in the Code tab and reply with `isn't available in this environment`. Edit [settings files](</docs/en/settings>) directly to manage permission rules and configuration, or run the command from the standalone CLI.
+ * **Terminal-dialog commands** : built-in commands that open an interactive panel in the terminal, such as `/permissions`, `/config`, and `/doctor`, are not available in the Code tab and reply with `isn't available in this environment`. Edit [settings files](</docs/en/settings>) directly to manage permission rules and configuration, or run the command from the standalone CLI.
##
--- a/desktop-linux.md
+++ b/desktop-linux.md
@@ -43,7 +43,7 @@
Launch and sign in
-Launch **Claude** from your application launcher, or run `claude-desktop` from a terminal, and sign in with your Anthropic account.
+Launch **Claude** from your application launcher, or run `claude-desktop` from a terminal, and sign in with your Anthropic account.The Linux app signs in the same way as on macOS and Windows: with a claude.ai subscription, or through your organization’s SSO. Desktop doesn’t accept a Claude Console API key directly; use the [CLI](</docs/en/quickstart>) for API-key authentication. For enterprise deployments that route Desktop to Google Cloud’s Agent Platform or an LLM gateway, see the [enterprise configuration guide](<https://support.claude.com/en/articles/12622667-enterprise-configuration>) and [network configuration](</docs/en/network-config>).
Verify the signing key
--- a/env-vars.md
+++ b/env-vars.md
@@ -133,6 +133,8 @@
`BASH_MAX_TIMEOUT_MS`| Maximum timeout the model can set for long-running bash commands (default: 600000, or 10 minutes)
`CCR_FORCE_BUNDLE`| Set to `1` to force [`claude --remote`](</docs/en/claude-code-on-the-web#send-local-repositories-without-github>) to bundle and upload your local repository even when GitHub access is available
`CLAUDECODE`| Set to `1` in subprocesses Claude Code spawns (Bash and PowerShell tools, tmux sessions, [hook](</docs/en/hooks>) commands, [status line](</docs/en/statusline>) commands, stdio [MCP server](</docs/en/mcp>) subprocesses). IDE extensions also set this in their integrated terminals. Use to detect when a script is running inside a subprocess spawned by Claude Code. To check whether the current process was spawned directly by a tool call or hook, rather than inside a stdio MCP server that Claude Code started, use `CLAUDE_CODE_CHILD_SESSION` instead
+`CLAUDE_AFK_COUNTDOWN_MS`| How many milliseconds before auto-continue the on-screen countdown appears on an unanswered `AskUserQuestion` dialog. Default `20000` (20 seconds). See `CLAUDE_AFK_TIMEOUT_MS`. Requires Claude Code v2.1.198 or later
+`CLAUDE_AFK_TIMEOUT_MS`| How many milliseconds of idle time before an unanswered [`AskUserQuestion`](</docs/en/tools-reference>) dialog auto-continues without you. Default `60000` (60 seconds). To keep questions open while you’re away, set a large value like `86400000` (24 hours). Setting `0` doesn’t turn the timeout off; it closes the dialog immediately. Requires Claude Code v2.1.198 or later
`CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS`| Set to `1` to disable all built-in [subagent](</docs/en/sub-agents>) types such as Explore and Plan. Only applies in non-interactive mode (the `-p` flag). Useful for SDK users who want a blank slate
`CLAUDE_AGENT_SDK_MCP_NO_PREFIX`| Set to `1` to skip the `mcp__<server>__` prefix on tool names from SDK-created MCP servers. Tools use their original names. SDK usage only
`CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`| Stall timeout in milliseconds for background subagents. Default `600000` (10 minutes). The timer resets on each streaming progress event; if no progress arrives within the window, the subagent is aborted and the task is marked failed, surfacing any partial result to the parent
@@ -150,6 +152,7 @@
`CLAUDE_CODE_ATTRIBUTION_HEADER`| Set to `0` to omit the attribution block (client version and prompt fingerprint) from the start of the system prompt. Disabling it improves prompt-cache hit rates when routing through an [LLM gateway](</docs/en/llm-gateway>). Anthropic API caching is unaffected
`CLAUDE_CODE_AUTO_COMPACT_WINDOW`| Set the context capacity in tokens used for auto-compaction calculations. Defaults to the model’s context window, 200K for standard models or 1M for [extended context](</docs/en/model-config#extended-context>) models, except on Sonnet 5, which has its own [default threshold](</docs/en/model-config#sonnet-5-context-window>). Use a lower value like `500000` on a 1M model to treat the window as 500K for compaction purposes. The value is capped at the model’s actual context window. `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` is applied as a percentage of this value. Setting this variable decouples the compaction threshold from the status line’s `used_percentage`, which always uses the model’s full context window
`CLAUDE_CODE_AUTO_CONNECT_IDE`| Override automatic [IDE connection](</docs/en/vs-code>). By default, Claude Code connects automatically when launched inside a supported IDE’s integrated terminal. Set to `false` to prevent this. Set to `true` to force a connection attempt when auto-detection fails, such as when tmux obscures the parent terminal. Takes precedence over the [`autoConnectIde`](</docs/en/settings#global-config-settings>) global config setting
+`CLAUDE_CODE_BRIDGE_SESSION_ID`| Set automatically in Bash tool and [hook command](</docs/en/hooks>) subprocesses while the session has an active [Remote Control](</docs/en/remote-control>) connection, and removed when the connection ends. The value is the session’s ID in `session_` form, the same identifier that appears in the session’s `claude.ai/code` URL, so a script can link back to the session that ran it. Requires Claude Code v2.1.199 or later. In [cloud sessions](</docs/en/claude-code-on-the-web>), read `CLAUDE_CODE_REMOTE_SESSION_ID` instead
`CLAUDE_CODE_CERT_STORE`| Comma-separated list of CA certificate sources for TLS connections. `bundled` is the Mozilla CA set shipped with Claude Code. `system` is the operating system trust store, read only on runtimes with `tls.getCACertificates`: the native binary, or Node 22.15 or later for npm installs. See [CA certificate store](</docs/en/network-config#ca-certificate-store>). Default is `bundled,system`
`CLAUDE_CODE_CHILD_SESSION`| Set to `1` in subprocesses Claude Code spawns via the Bash, PowerShell, and Monitor tools, [hook](</docs/en/hooks>) commands, and [status line](</docs/en/statusline>) commands. Not set for stdio [MCP server](</docs/en/mcp>) subprocesses, which are long-lived and outlive the session that spawned them. Unlike `CLAUDECODE`, this is only set by Claude Code itself when it launches a subprocess and not by IDE extensions, so it reliably distinguishes a nested session from a top-level `claude` launched in an IDE-integrated terminal. A nested interactive `claude` TUI started this way is automatically excluded from `--resume`, `--continue`, up-arrow history, and the `claude agents` list. Non-interactive `claude -p` sessions still persist. Set `CLAUDE_CODE_FORCE_SESSION_PERSISTENCE=1` to override this exclusion. Requires Claude Code v2.1.172 or later
`CLAUDE_CODE_CLIENT_CERT`| Path to client certificate file for mTLS authentication
@@ -160,19 +163,20 @@
`CLAUDE_CODE_DEBUG_LOG_LEVEL`| Minimum log level written to the debug log file. Values: `verbose`, `debug` (default), `info`, `warn`, `error`. Set to `verbose` to include high-volume diagnostics like full status line command output, or raise to `error` to reduce noise
`CLAUDE_CODE_DISABLE_1M_CONTEXT`| Set to `1` to disable [1M context window](</docs/en/model-config#extended-context>) support. When set, 1M model variants are unavailable in the model picker, and [Sonnet 5](</docs/en/model-config#sonnet-5-context-window>) sessions are treated as having a 200K window. Useful for enterprise environments with compliance requirements
`CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING`| Set to `1` to disable [adaptive reasoning](</docs/en/model-config#adjust-effort-level>) on Opus 4.6 and Sonnet 4.6 and fall back to the fixed thinking budget controlled by `MAX_THINKING_TOKENS`. From v2.1.111, has no effect on Fable 5, Sonnet 5, or Opus 4.7 and later, which always use adaptive reasoning
-`CLAUDE_CODE_DISABLE_ADVISOR_TOOL`| Set to `1` to disable the [advisor tool](</docs/en/advisor>). The `/advisor` command and `--advisor` flag become unavailable and any configured `advisorModel` is ignored. Requires Claude Code v2.1.98 or later
+`CLAUDE_CODE_DISABLE_ADVISOR_TOOL`| Set to `1` to disable the [advisor tool](</docs/en/advisor>). The `/advisor` command becomes unavailable, any configured `advisorModel` is ignored, and the `--advisor` flag is accepted but has no effect, so existing scripts that pass it continue to work without errors. Requires Claude Code v2.1.98 or later
`CLAUDE_CODE_DISABLE_AGENT_VIEW`| Set to `1` to turn off [background agents and agent view](</docs/en/agent-view>): `claude agents`, `--bg`, `/background`, and the on-demand supervisor. Equivalent to the [`disableAgentView`](</docs/en/settings#available-settings>) setting
`CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN`| Set to `1` to disable [fullscreen rendering](</docs/en/fullscreen>) and use the classic main-screen renderer. The conversation stays in your terminal’s native scrollback so `Cmd+f` and tmux copy mode work as usual. Takes precedence over `CLAUDE_CODE_NO_FLICKER` and the [`tui`](</docs/en/settings#available-settings>) setting. You can also switch with `/tui default`. Does not apply to background sessions opened from [agent view](</docs/en/agent-view>), which always use fullscreen rendering
`CLAUDE_CODE_DISABLE_ARTIFACT`| Set to `1` to disable the [Artifact](</docs/en/artifacts>) tool, which publishes session output as a private web page on claude.ai. Equivalent to the [`disableArtifact`](</docs/en/settings#available-settings>) setting
`CLAUDE_CODE_DISABLE_ATTACHMENTS`| Set to `1` to disable attachment processing. File mentions with `@` syntax are sent as plain text instead of being expanded into file content
`CLAUDE_CODE_DISABLE_AUTO_MEMORY`| Set to `1` to disable [auto memory](</docs/en/memory#auto-memory>). Set to `0` to force auto memory on even when `--bare` mode or [`autoMemoryEnabled: false`](</docs/en/settings#available-settings>) would otherwise disable it. When disabled, Claude does not create or load auto memory files
`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`| Set to `1` to disable all background task functionality, including the `run_in_background` parameter on Bash and subagent tools, auto-backgrounding, and the Ctrl+B shortcut
-`CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF`| Set to `1` to stop a [background session’s](</docs/en/agent-view>) running background shell commands and dynamic workflows when the [supervisor](</docs/en/agent-view#the-supervisor-process>) stops, restarts, or updates that session’s process, instead of handing them to the session’s next process. Affects only that handoff: backgrounding a session with `←` or [`/background`](</docs/en/agent-view#from-inside-a-session>) still carries in-flight work over, and `CLAUDE_DISABLE_ADOPT` turns off both. Requires Claude Code v2.1.196 or later
+`CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF`| Set to `1` to stop a [background session’s](</docs/en/agent-view>) running background shell commands, dynamic workflows, and, as of v2.1.198, background subagents when the [supervisor](</docs/en/agent-view#the-supervisor-process>) stops, restarts, or updates that session’s process, instead of handing them to the session’s next process. Affects only that handoff: backgrounding a session with `←` or [`/background`](</docs/en/agent-view#from-inside-a-session>) still carries in-flight work over, and `CLAUDE_DISABLE_ADOPT` turns off both. Requires Claude Code v2.1.196 or later
`CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP`| Set to `1` to stop Claude Code from terminating [background shell commands](</docs/en/interactive-mode#background-bash-commands>) when the operating system reports memory pressure. By default, on macOS and Linux, Claude Code terminates a background shell started in the main session on a memory-pressure signal once the session has been idle for 30 minutes and no turn or subagent is running. Windows has no memory-pressure signal, so this variable has no effect there. Requires Claude Code v2.1.193 or later
`CLAUDE_CODE_DISABLE_BUNDLED_SKILLS`| Set to `1` to disable the [skills](</docs/en/skills>) and workflows that ship with Claude Code: bundled skills and workflows are removed entirely, while built-in slash commands like `/init` stay typable but are hidden from the model. Skills from plugins, `.claude/skills/`, and `.claude/commands/` are unaffected. Equivalent to the [`disableBundledSkills`](</docs/en/settings#available-settings>) setting; `0` does not override it
`CLAUDE_CODE_DISABLE_CLAUDE_MDS`| Set to `1` to prevent loading any CLAUDE.md memory files into context, including user, project, and auto-memory files
`CLAUDE_CODE_DISABLE_CRON`| Set to `1` to disable [scheduled tasks](</docs/en/scheduled-tasks>). The `/loop` skill and cron tools become unavailable and any already-scheduled tasks stop firing, including tasks that are already running mid-session
`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`| Set to `1` to strip Anthropic-specific `anthropic-beta` request headers and beta tool-schema fields (such as `defer_loading` and `eager_input_streaming`) from API requests. Use this when a proxy gateway rejects requests with errors like “Unexpected value(s) for the `anthropic-beta` header” or “Extra inputs are not permitted”. Standard fields (`name`, `description`, `input_schema`, `cache_control`) are preserved
+`CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS`| Set to `1` to disable the built-in [Explore and Plan subagents](</docs/en/sub-agents#built-in-subagents>). Claude explores with its search tools or the general-purpose subagent instead, and [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) reads files directly rather than launching Explore and Plan agents. Custom subagents named `Explore` or `Plan` are unaffected. To remove every built-in subagent type in the Agent SDK or non-interactive mode, use `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` instead. Requires Claude Code v2.1.198 or later
`CLAUDE_CODE_DISABLE_FAST_MODE`| Set to `1` to disable [fast mode](</docs/en/fast-mode>)
`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY`| Set to `1` to disable the “How is Claude doing?” session quality surveys. Surveys are also disabled when `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set, unless `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL` opts back in. To set a sample rate instead of disabling outright, use the [`feedbackSurveyRate`](</docs/en/settings#available-settings>) setting. See [Session quality surveys](</docs/en/data-usage#session-quality-surveys>)
`CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING`| Set to `1` to disable file [checkpointing](</docs/en/checkpointing>). The `/rewind` command will not be able to restore code changes
@@ -218,7 +222,7 @@
`CLAUDE_CODE_IDE_SKIP_VALID_CHECK`| Set to `1` to skip validation of IDE lockfile entries during connection. Use when auto-connect fails to find your IDE despite it running
`CLAUDE_CODE_MAX_CONTEXT_TOKENS`| Override the context window size Claude Code assumes for the active model. As of v2.1.193, applied directly for model names Claude Code does not recognize as a Claude model; for recognized Claude models it only takes effect when `DISABLE_COMPACT` is also set. Use this when routing to a model through `ANTHROPIC_BASE_URL` whose context window does not match the built-in size for its name
`CLAUDE_CODE_MAX_OUTPUT_TOKENS`| Set the maximum number of output tokens for most requests. Defaults and caps vary by model; see [max output tokens](<https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison>). Increasing this value reduces the effective context window available before [auto-compaction](</docs/en/costs#reduce-token-usage>) triggers
-`CLAUDE_CODE_MAX_RETRIES`| Override the number of times to retry failed API requests (default: 10). Capped at 15 as of v2.1.186. For unattended sessions that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG` instead
+`CLAUDE_CODE_MAX_RETRIES`| Override the number of times to retry failed API requests (default: 10). Capped at 15 as of v2.1.186; as of v2.1.199, `CLAUDE_CODE_RETRY_WATCHDOG` raises the default and removes the cap. For unattended sessions that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG` instead
`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
@@ -250,7 +254,7 @@
`CLAUDE_CODE_REMOTE_SESSION_ID`| Set automatically in [cloud sessions](</docs/en/claude-code-on-the-web>) to the current session’s ID. Read this to construct a link back to the session transcript. See [Link output back to the session](</docs/en/claude-code-on-the-web#link-output-back-to-the-session>)
`CLAUDE_CODE_RESUME_INTERRUPTED_TURN`| Set to `1` to automatically resume if the previous session ended mid-turn. Used in SDK mode so the model continues without requiring the SDK to re-send the prompt
`CLAUDE_CODE_RESUME_PROMPT`| Override the continuation message injected when resuming a session that ended mid-turn. Defaults to `Continue from where you left off.`. Spawn scripts for long-running agents can set this to a more directive boot message. An empty string uses the default
-`CLAUDE_CODE_RETRY_WATCHDOG`| Set to `1` for unattended sessions such as eval harnesses, CI jobs, or remote workers. Retries `429` and `529` capacity errors indefinitely instead of failing after `CLAUDE_CODE_MAX_RETRIES` attempts. The watchdog backs off up to 5 minutes between attempts, or until the limit resets when the response carries a rate-limit reset time, so a session that hits a usage limit waits out the remaining window. Requires Claude Code v2.1.186 or later
+`CLAUDE_CODE_RETRY_WATCHDOG`| Set to `1` for unattended sessions such as eval harnesses, CI jobs, or remote workers. Retries `429` and `529` capacity errors indefinitely instead of failing after `CLAUDE_CODE_MAX_RETRIES` attempts. The watchdog backs off up to 5 minutes between attempts, or until the limit resets when the response carries a rate-limit reset time, so a session that hits a usage limit waits out the remaining window. As of v2.1.199 it also raises the default retry count for other transient errors, such as server errors, timeouts, and dropped connections, to 300, roughly three hours of backoff, and removes the cap of 15 on `CLAUDE_CODE_MAX_RETRIES` if you set that variable explicitly. Requires Claude Code v2.1.186 or later
`CLAUDE_CODE_SAFE_MODE`| Set to `1` to start in safe mode: CLAUDE.md, skills, plugins, hooks, MCP servers, custom commands and agents, output styles, workflows, custom themes, custom keybindings, status line and file-suggestion commands, LSP servers, and auto-memory do not load, for troubleshooting a broken configuration. Managed settings policy still applies, including policy-configured hooks, status line, and file-suggestion commands; managed plugins, managed skills, managed CLAUDE.md, and policy-configured MCP servers do not. Equivalent to passing [`--safe-mode`](</docs/en/cli-reference#cli-flags>). Directly spawned child processes inherit the variable
`CLAUDE_CODE_SCRIPT_CAPS`| JSON object limiting how many times specific scripts may be invoked per session when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set. Keys are substrings matched against the command text; values are integer call limits. For example, `{"deploy.sh": 2}` allows `deploy.sh` to be called at most twice. Matching is substring-based so shell-expansion tricks like `./scripts/deploy.sh $(evil)` still count against the cap. Runtime fan-out via `xargs` or `find -exec` is not detected; this is a defense-in-depth control
`CLAUDE_CODE_SCROLL_SPEED`| Set the mouse wheel scroll multiplier in [fullscreen rendering](</docs/en/fullscreen#mouse-wheel-scrolling>). Accepts values from 1 to 20, and fractional values below 1 such as `0.5` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events. Set to `3` to match `vim` if your terminal sends one wheel event per notch without amplification. Ignored in the JetBrains IDE terminal, where Claude Code uses its own scroll handling
@@ -286,7 +290,7 @@
`CLAUDE_CODE_USE_NATIVE_FILE_SEARCH`| Set to `1` to discover custom commands, subagents, and output styles using Node.js file APIs instead of ripgrep. Set this if the bundled ripgrep binary is unavailable or blocked in your environment. Does not affect the Grep or file search tools
`CLAUDE_CODE_USE_POWERSHELL_TOOL`| Controls the PowerShell tool. On Windows without Git Bash, the tool is enabled automatically; set to `0` to disable it. On Windows with Git Bash installed, the tool is rolling out progressively: set to `1` to opt in or `0` to opt out. On Linux, macOS, and WSL, set to `1` to enable it, which requires `pwsh` on your `PATH`. When enabled on Windows, Claude can run PowerShell commands natively instead of routing through Git Bash. See [PowerShell tool](</docs/en/tools-reference#powershell-tool>)
`CLAUDE_CODE_USE_VERTEX`| Use [Vertex](</docs/en/google-vertex-ai>)
-`CLAUDE_CONFIG_DIR`| Override the configuration directory (default: `~/.claude`). All settings, credentials, session history, and plugins are stored under this path. Useful for running multiple accounts side by side: for example, `alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'`
+`CLAUDE_CONFIG_DIR`| Override the configuration directory (default: `~/.claude`). All settings, session history, and plugins are stored under this path, as are credentials on Linux and Windows; on macOS, credentials are in the system Keychain. Useful for running multiple accounts side by side: for example, `alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'`
`CLAUDE_DISABLE_ADOPT`| Set to `1` to stop in-flight background work instead of carrying it over when you background a session by pressing `←` or with [`/background`](</docs/en/agent-view#from-inside-a-session>). Claude Code asks you to confirm before backgrounding, then stops the tasks that would otherwise carry over. Requires Claude Code v2.1.195 or later
`CLAUDE_EFFORT`| Set automatically in Bash tool subprocesses and hook commands to the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `low`, `medium`, `high`, `xhigh`, or `max`. Ultracode is not a distinct level and reports as `xhigh`. Matches the `effort.level` field passed to [hooks](</docs/en/hooks>). Only set when the current model supports the effort parameter
`CLAUDE_ENABLE_BYTE_WATCHDOG`| Set to `1` to force-enable the byte-level streaming idle watchdog, or set to `0` to force-disable it. When unset, the watchdog is enabled by default for direct Anthropic API and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) connections. The byte watchdog aborts a connection when no bytes arrive on the wire for 180 seconds by default on direct Anthropic API connections, 300 seconds on Claude Platform on AWS and when enabled on Bedrock, or for the value of `CLAUDE_STREAM_IDLE_TIMEOUT_MS` when that is set, which is clamped to a minimum of 5 minutes, independent of the event-level watchdog
Show diff (407 lines)
--- a/errors.md
+++ b/errors.md
@@ -15,9 +15,12 @@
`API Error: 500 Internal server error`| Server errors
`API Error: Repeated 529 Overloaded errors`| Server errors
`Request timed out`| Server errors, or Network if the message mentions your internet connection
+`Server error mid-response. The response above may be incomplete.`| Server errors
+`Connection closed mid-response` / `Response stalled mid-stream`| Server errors
`<model> is temporarily unavailable, so auto mode cannot determine the safety of...`| Server errors
`Auto mode could not evaluate this action and is blocking it for safety`| Server errors
`Auto mode classifier transcript exceeded context window`| Server errors
+`Agent terminated early due to an API error`| Server errors
`You've hit your session limit` / `You've hit your weekly limit`| Usage limits
`Usage credits required for 1M context`| Usage limits
`Server is temporarily limiting requests`| Usage limits
@@ -33,9 +36,12 @@
`Remote Control is only available when using Claude via api.anthropic.com`| Authentication
`OAuth token revoked` / `OAuth token has expired`| Authentication
`does not meet scope requirement user:profile`| Authentication
+`AWS credentials expired or invalid`| Authentication
+`AWS authentication failed`| Authentication
`Unable to connect to API`| Network
`Waiting for API response · will retry in`| Automatic retries, or Network if it persists
`SSL certificate verification failed`| Network
+`SSL certificate error (...)` during login or startup| Network
`403` with `x-deny-reason: host_not_allowed` in a cloud or routine session| Network
`Prompt is too long`| Request errors
`Error during compaction: Conversation too long`| Request errors
@@ -51,6 +57,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
+`--bg and --print conflict`| Command-line errors
Responses seem lower quality than usual| Response quality
##
@@ -59,12 +66,17 @@
Automatic retries
-Claude Code retries transient failures before showing you an error. Server errors, overloaded responses, request timeouts, temporary 429 throttles, and dropped connections are all retried up to 10 times with exponential backoff. While retrying, the spinner shows a `Retrying in Ns · attempt x/y` countdown. If no data arrives on the response stream for 20 seconds while a request is still pending, the spinner shows `Waiting for API response · will retry in … · check your network` before any retry has started. The request has not failed yet: the countdown runs to the point where Claude Code aborts the stalled connection and retries, so the banner clears on its own once data resumes or the retry succeeds. As of v2.1.185 the threshold is 20 seconds; earlier versions show the banner after 10 seconds with different wording. If it reappears on every attempt, treat it as a network issue. When you see one of the errors on this page, those retries have already been exhausted. You can tune the behavior with these environment variables:
+Claude Code retries transient failures before showing you an error. Server errors, overloaded responses, request timeouts, temporary 429 throttles, and dropped connections are all retried up to 10 times with exponential backoff. As of v2.1.198, this covers connections that drop in the middle of a response before any visible output has streamed: Claude Code re-issues the request with the same backoff and the turn continues instead of stopping with a connection error. As of v2.1.199, temporary 429 throttles that don’t carry your plan’s quota headers are also retried when you’re signed in with a claude.ai subscription; earlier versions retried them only for API key and Enterprise sign-ins. Two failure classes aren’t retried, because a retry can’t succeed:
+
+ * As of v2.1.199, a TLS certificate validation failure, such as a TLS-inspecting proxy, a missing `NODE_EXTRA_CA_CERTS` bundle, or an expired certificate, fails on the first attempt so the fix appears immediately instead of after the full retry budget. See SSL certificate errors. Transient TLS conditions such as a handshake timeout still retry.
+ * As of v2.1.199, a server error that arrives after Claude has already streamed visible output keeps the partial response and appends an incomplete-response notice instead of retrying, since re-running the request could execute the same tools twice. Earlier versions discarded the partial output and reported the turn as an error.
+
+While retrying, the spinner shows a `Retrying in Ns · attempt x/y` countdown after an error label. The label names the specific reason from the first attempt for failures you can act on right away: the network is down, a TLS handshake failed, or you hit a rate limit. For other errors it reads `API error` at first. As of v2.1.198 it switches to the specific reason from the third attempt, or on the final attempt when `CLAUDE_CODE_MAX_RETRIES` allows fewer than three; earlier versions switch only on the final attempt. As of v2.1.198, the usual spinner tip is suppressed during retries. Once the error reason is revealed, if the failure is a 529 overload the line below the countdown also names where to check service status: `status.claude.com` on the Anthropic API, or the provider or gateway host named in the message on other configurations. If no data arrives on the response stream for 20 seconds while a request is still pending, the spinner shows `Waiting for API response · will retry in … · check your network` before any retry has started. The request has not failed yet: the countdown runs to the point where Claude Code aborts the stalled connection and retries, so the banner clears on its own once data resumes or the retry succeeds. As of v2.1.185 the threshold is 20 seconds; earlier versions show the banner after 10 seconds with different wording. If it reappears on every attempt, treat it as a network issue. When you see one of the errors on this page, those retries have already been exhausted, unless it belongs to a class that isn’t retried, such as a certificate-validation failure. You can tune the behavior with these environment variables:
Variable| Default| Effect
---|---|---
-[`CLAUDE_CODE_MAX_RETRIES`](</docs/en/env-vars>)| 10| Number of retry attempts. Capped at 15 as of v2.1.186. Lower it to surface failures faster in scripts.
-[`CLAUDE_CODE_RETRY_WATCHDOG`](</docs/en/env-vars>)| unset| Set to `1` in unattended sessions such as CI jobs to retry `429` and `529` capacity errors indefinitely instead of failing after `CLAUDE_CODE_MAX_RETRIES` attempts.
+[`CLAUDE_CODE_MAX_RETRIES`](</docs/en/env-vars>)| 10| Number of retry attempts. Capped at 15 as of v2.1.186; as of v2.1.199 `CLAUDE_CODE_RETRY_WATCHDOG` raises the default and removes the cap. Lower it to surface failures faster in scripts.
+[`CLAUDE_CODE_RETRY_WATCHDOG`](</docs/en/env-vars>)| unset| Set to `1` in unattended sessions such as CI jobs to retry `429` and `529` capacity errors indefinitely instead of failing after `CLAUDE_CODE_MAX_RETRIES` attempts. As of v2.1.199 it also raises the default retry count for other transient errors, such as server errors, timeouts, and dropped connections, to 300, roughly three hours of backoff, and removes the cap of 15 on `CLAUDE_CODE_MAX_RETRIES` if you set that variable explicitly.
[`API_TIMEOUT_MS`](</docs/en/env-vars>)| 600000| Per-request timeout in milliseconds. Raise it for slow networks or proxies.
##
@@ -101,7 +113,7 @@
API Error: Repeated 529 Overloaded errors. The API is at capacity — this is usually temporary. Try again in a moment. If it persists, check https://status.claude.com.
-The trailing sentence varies by provider in the same way as the 500 error above. A 529 is not your usage limit and does not count against your quota. **What to do:**
+The trailing sentence varies by provider in the same way as the 500 error above. A 529 is not your usage limit and doesn’t count against your quota. **What to do:**
* Check [status.claude.com](<https://status.claude.com>), or the provider status page named in the message, for capacity notices
* Try again in a few minutes
@@ -113,11 +125,11 @@
Request timed out
-The API did not respond before the connection deadline.
+The API didn’t respond before the connection deadline.
Request timed out
-This can happen during periods of high load or when a very large response is being generated. The default request timeout is 10 minutes. **What to do:**
+This can happen during periods of high load or when the model is generating a very large response. The default request timeout is 10 minutes. **What to do:**
* Retry the request
* For long-running tasks, break the work into smaller prompts
@@ -128,9 +140,31 @@
+The response above may be incomplete
+
+A streaming response failed after Claude had already produced visible output. Re-sending the request could run the same tool calls twice, so Claude Code keeps what already streamed and appends this notice instead of discarding the turn. Which variant you see names the cause:
+
+ API Error: Server error mid-response. The response above may be incomplete.
+ API Error: Connection closed mid-response. The response above may be incomplete.
+ API Error: Response stalled mid-stream. The response above may be incomplete.
+
+ * `Server error mid-response`: a mid-stream overloaded or 5xx server error. This variant requires Claude Code v2.1.199 or later; before then that case discarded the partial output and reported the whole turn as an error.
+ * `Connection closed mid-response`: the connection dropped.
+ * `Response stalled mid-stream`: the stream stopped sending data.
+
+**What to do:**
+
+ * Read the response that streamed. Nothing has been lost, but the final sentences or tool calls may be missing.
+ * Reply with `continue` to have Claude pick up where it stopped
+ * If the same error appears before any visible output, Claude Code retries the request instead of finalizing it. See Automatic retries.
+
+###
+
+
+
Auto mode cannot determine the safety of an action
-The model that [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) uses to classify actions could not produce a decision, so auto mode did not approve the action automatically. The message you see depends on why the classifier failed. Reads, searches, and edits inside your working directory skip the classifier, so they keep working in all of these cases. When the classifier model is overloaded:
+The model that [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) uses to classify actions couldn’t produce a decision, so auto mode didn’t approve the action automatically. The message you see depends on why the classifier failed. Reads, searches, and edits inside your working directory skip the classifier, so they keep working in all of these cases. When the classifier model is overloaded:
<model> is temporarily unavailable, so auto mode cannot determine the safety of <tool> right now. Wait briefly and then try this action again.
@@ -138,7 +172,7 @@
* Retry after a few seconds; Claude sees the same message and usually retries on its own
* If retries keep failing, continue with read-only tasks and come back to the blocked action later
- * This is transient and unrelated to [auto mode eligibility](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>); you do not need to change settings
+ * This is transient and unrelated to [auto mode eligibility](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>); you don’t need to change settings
When the classifier returned an unparseable response:
@@ -155,7 +189,7 @@
**What to do:**
- * This is not a decision about your action. A safety filter on the API was triggered by existing content in your conversation when auto mode sent the conversation to the classifier
+ * This is not a decision about your action. Content already in your conversation triggered a safety filter on the API when auto mode sent the conversation to the classifier
* Retrying will not help; the same conversation content will trigger the filter again
* Switch to a different [permission mode](</docs/en/permission-modes>) so you can approve the action when prompted, or start a fresh conversation without the triggering content
@@ -163,10 +197,27 @@
Auto mode classifier transcript exceeded context window — falling back to manual approval (try /compact to reduce conversation size)
-In an interactive session, auto mode falls back to a normal permission prompt for that action so you can approve or deny it manually. In [non-interactive mode](</docs/en/headless>) the run aborts because the transcript only grows and retrying cannot succeed. **What to do:**
+In an interactive session, auto mode falls back to a normal permission prompt for that action so you can approve or deny it manually. In [non-interactive mode](</docs/en/headless>) the run aborts because the transcript only grows and retrying can’t succeed. **What to do:**
* Approve or deny the action in the prompt that appears
* Run `/compact` to reduce the conversation size so subsequent actions fit within the classifier window again
+
+###
+
+
+
+Agent terminated early due to an API error
+
+A [subagent](</docs/en/sub-agents>)’s API request failed terminally, for example because a usage limit was reached or retries for a server error ran out, so the subagent stopped before finishing its task. This message requires Claude Code v2.1.199 or later; before then the API error text was returned to Claude as if it were the subagent’s result.
+
+ Agent terminated early due to an API error: <error detail>
+
+**What to do:**
+
+ * Match the error detail after the colon to its own section on this page, such as Usage limits or Server errors, and follow that section’s steps
+ * Once the underlying error clears, ask Claude to retry the task or [resume the subagent](</docs/en/sub-agents#resume-subagents>)
+
+When a rate limit, overload, or server error interrupts a foreground subagent that already produced output, Claude receives that partial output marked as incomplete instead of this error. See [API errors in subagents](</docs/en/sub-agents#api-errors-in-subagents>).
##
@@ -224,7 +275,7 @@
API Error: Server is temporarily limiting requests (not your usage limit)
-This is retried automatically before being shown. **What to do:**
+Claude Code tells these apart from your plan limit by the absence of the unified quota headers a real limit response carries. As of v2.1.199 this is retried automatically with backoff before being shown, whichever way you authenticate. On earlier versions, a session signed in with a claude.ai subscription failed the turn on the first occurrence; only API key and Enterprise sign-ins retried it. **What to do:**
* Wait briefly and try again
* Check [status.claude.com](<https://status.claude.com>) if it persists
@@ -285,7 +336,7 @@
* Run `/login` to authenticate with your Claude subscription or Console account
* If you expected an environment variable to authenticate you, confirm `ANTHROPIC_API_KEY` is set and exported in the shell where you launched `claude`
* For CI or automation where interactive login is not possible, configure an [`apiKeyHelper`](</docs/en/settings#available-settings>) script that fetches a key at startup
- * See [Authentication precedence](</docs/en/authentication#authentication-precedence>) to understand which credential wins when several are present
+ * See [Authentication precedence](</docs/en/authentication#authentication-precedence>) to understand which credential Claude Code uses when several are present
If you are prompted to log in repeatedly, see [Not logged in or token expired](</docs/en/troubleshoot-install#not-logged-in-or-token-expired>) for system clock and macOS Keychain fixes.
@@ -295,7 +346,7 @@
Could not resolve authentication method
-The session reached the API client without any credential. This appears in [background sessions](</docs/en/agent-view>), cloud sessions, and Agent SDK contexts where the interactive login check does not run before the first request.
+The session reached the API client without any credential. This appears in [background sessions](</docs/en/agent-view>), cloud sessions, and Agent SDK contexts where the interactive login check doesn’t run before the first request.
Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted
@@ -347,14 +398,14 @@
Your organization has disabled API key authentication
-Your Console organization’s admin has turned off API key authentication, so the API rejects the key Claude Code is sending. The recovery hint after the `·` varies by where the key came from:
+This message requires Claude Code v2.1.169 or later. Your Console organization’s admin has turned off API key authentication, so the API rejects the key Claude Code is sending. The recovery hint after the `·` varies by where the key came from:
Your organization has disabled API key authentication · Run /login to sign in with your claude.ai account
Your organization has disabled API key authentication · Unset ANTHROPIC_API_KEY to use your claude.ai account instead
Your organization has disabled API key authentication · Unset ANTHROPIC_API_KEY and run /login to sign in with your claude.ai account
Your organization has disabled API key authentication · Unset the apiKeyHelper setting and run /login to sign in with your claude.ai account
-Environment variables and `apiKeyHelper` take precedence over `/login`, so running `/login` alone does not help while either is still supplying a key. See [Authentication precedence](</docs/en/authentication#authentication-precedence>). **What to do:**
+Environment variables and `apiKeyHelper` take precedence over `/login`, so running `/login` alone doesn’t help while either is still supplying a key. See [Authentication precedence](</docs/en/authentication#authentication-precedence>). **What to do:**
* If the message names `ANTHROPIC_API_KEY`, unset it in the current shell and remove it from your shell profile or `.env` file, then relaunch `claude`
* If the message names `apiKeyHelper`, remove the [`apiKeyHelper`](</docs/en/settings#available-settings>) setting from your `settings.json`
@@ -368,11 +419,11 @@
Your organization has disabled Claude subscription access
-Your Claude organization does not allow signing in to Claude Code with a subscription login. Running `/login` again with the same account returns the same error.
+Your Claude organization doesn’t allow signing in to Claude Code with a subscription login. Running `/login` again with the same account returns the same error.
Your organization has disabled Claude subscription access for Claude Code · Use an Anthropic API key instead, or ask your admin to enable access
-This is a server-side organization setting, so it cannot be overridden from local settings, environment variables, or CLI flags. The Agent SDK and `-p` non-interactive mode surface this as the `oauth_org_not_allowed` error code. **What to do:**
+This is a server-side organization setting, so it can’t be overridden from local settings, environment variables, or CLI flags. The Agent SDK and `-p` non-interactive mode surface this as the `oauth_org_not_allowed` error code. **What to do:**
* Ask your admin to enable Claude Code access for your organization
* Authenticate with a Console API key instead of your subscription. See [Claude Console authentication](</docs/en/authentication#claude-console-authentication>) for setup.
@@ -388,7 +439,7 @@
Routines are disabled by your organization's policy.
-This is a server-side setting, so it cannot be overridden from local settings, environment variables, or CLI flags. **What to do:**
+This is a server-side setting, so it can’t be overridden from local settings, environment variables, or CLI flags. **What to do:**
* Ask an Owner in your organization to enable the **Routines** toggle at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>)
* For one-off scheduled work that does not require organization-level routines, see [scheduled tasks](</docs/en/scheduled-tasks>)
@@ -439,7 +490,39 @@
**What to do:**
- * Run `/login` to mint a new token with the current scopes. You do not need to log out first.
+ * Run `/login` to get a new token with the current scopes. You don’t need to log out first.
+
+###
+
+
+
+AWS credentials expired or invalid
+
+This message requires Claude Code v2.1.198 or later and only appears when [`awsAuthRefresh`](</docs/en/amazon-bedrock#advanced-credential-configuration>) is set in your settings file. Your AWS session token expired or was rejected, and the automatic refresh Claude Code already ran didn’t produce a credential the API accepts. It appears on a 401 from [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) or the [Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>), which is how those providers report an expired security token. The action hint in the middle names the `awsAuthRefresh` command from your settings, so it varies. The stable part is the leading `AWS credentials expired or invalid`:
+
+ AWS credentials expired or invalid · run /login and select "Claude Platform on AWS · refresh credentials", or run `aws sso login --profile myprofile` in another terminal · API Error: 401 ...
+
+Without `awsAuthRefresh` configured, the same 401 shows the generic `Please run /login` message instead, which can’t refresh AWS credentials. **What to do:**
+
+ * Run the `awsAuthRefresh` command named in the message, such as `aws sso login --profile myprofile`, in another terminal and complete the browser sign-in, then retry
+ * In an interactive session, run `/login`, choose **3rd-party platform** , then select **Claude Platform on AWS · refresh credentials** under **Using 3rd-party platforms** to run the same command without restarting Claude Code. See [Configure AWS credentials](</docs/en/claude-platform-on-aws#1-configure-aws-credentials>)
+ * If the error repeats after the refresh command succeeds, confirm the identity is valid outside Claude Code with `aws sts get-caller-identity` in the same shell and profile
+
+###
+
+
+
+AWS authentication failed
+
+This message requires Claude Code v2.1.198 or later and only appears when [`awsAuthRefresh`](</docs/en/amazon-bedrock#advanced-credential-configuration>) is set in your settings file. Your AWS provider returned a 403, or [Amazon Bedrock](</docs/en/amazon-bedrock>) returned a 401. Claude Code can’t tell which cause you hit. Amazon Bedrock reports an expired security token as a 403, but a 403 is also how it reports an authorization denial, such as an `AccessDeniedException` from a missing IAM permission or a model that isn’t enabled for your account. A 401 from Amazon Bedrock also lands here rather than under AWS credentials expired or invalid, because Bedrock doesn’t report an expired token as a 401. A 401 from that endpoint typically comes from something else in the request path, such as a corporate proxy. A credential refresh fixes an expired token and can’t fix the other causes, so the message offers both:
+
+ AWS authentication failed · run /login and select "Claude Platform on AWS · refresh credentials", or run `aws sso login --profile myprofile` in another terminal · if credentials are current, check AWS permissions and model access · API Error: 403 ...
+
+The action hint in the middle names the `awsAuthRefresh` command from your settings, so it varies. The stable part is the leading `AWS authentication failed`. **What to do:**
+
+ * Run the `awsAuthRefresh` command named in the message, or `aws sso login`, in case an expired credential is the cause
+ * If your credentials are current, confirm the IAM permissions in [IAM configuration](</docs/en/amazon-bedrock#iam-configuration>) are attached to the identity you’re using and that the selected model is enabled for your account and region
+ * Run `aws sts get-caller-identity` to confirm which identity your requests use; a stale `AWS_PROFILE` or default profile is a common cause of a permission mismatch
##
@@ -489,11 +572,15 @@
Unable to connect to API: SSL certificate verification failed. Check your proxy or corporate SSL certificates
Unable to connect to API: Self-signed certificate detected
+As of v2.1.199, a certificate validation failure isn’t retried, so this error appears on the first attempt instead of after the full retry budget. Earlier versions spent a few minutes retrying before showing it. Transient TLS conditions, such as a handshake timeout, still retry. During `/login` and the startup connectivity check, the same failure is reported with the OpenSSL code and the fix inline:
+
+ SSL certificate error (UNABLE_TO_GET_ISSUER_CERT_LOCALLY). If you are behind a corporate proxy or TLS-intercepting firewall, set NODE_EXTRA_CA_CERTS to your CA bundle path, or ask IT to allowlist *.anthropic.com. Run /doctor for details.
+
**What to do:**
* Export your organization’s CA bundle and point Claude Code at it with `NODE_EXTRA_CA_CERTS=/path/to/ca-bundle.pem`
* See [Network configuration](</docs/en/network-config#custom-ca-certificates>) for full setup instructions
- * Do not set `NODE_TLS_REJECT_UNAUTHORIZED=0`, which disables certificate validation entirely
+ * Don’t set `NODE_TLS_REJECT_UNAUTHORIZED=0`, which disables certificate validation entirely
###
@@ -556,7 +643,7 @@
This can happen when the window is already full at the moment auto-compact triggers, or when you run `/compact` after seeing `Prompt is too long`. **What to do:**
* Press Esc twice to open the message list and step back several turns. This drops the most recent messages from context. Then run `/compact` again.
- * If stepping back does not free enough space, run `/clear` to start a fresh session. Your previous conversation is preserved and can be reopened with `/resume`.
+ * If stepping back doesn’t free enough space, run `/clear` to start a fresh session. Your previous conversation is preserved and can be reopened with `/resume`.
###
@@ -596,14 +683,14 @@
Unable to resize image
-Claude Code could not downscale an attached image before sending it to the API.
+Claude Code couldn’t downscale an attached image before sending it to the API.
Unable to resize image — image processing is unavailable and dimensions could not be read from the file header. Please convert the image to PNG, JPEG, GIF, or WebP.
Unable to resize image — dimensions exceed the 2000x2000px limit and image processing failed. Please resize the image to reduce its pixel dimensions.
Unable to resize image (… raw, … base64). The image exceeds the … API limit and compression failed. Please resize the image manually or use a smaller image.
Unable to resize image — could not verify image dimensions are within the 2000x2000px API limit.
-Claude Code normally resizes large images automatically. These errors mean the native image processor failed to load or returned an error, so the image could not be resized to fit within API limits. **What to do:**
+Claude Code normally resizes large images automatically. These errors mean the native image processor failed to load or returned an error, so the image couldn’t be resized to fit within API limits. **What to do:**
* If the message asks you to convert the image, convert it to PNG, JPEG, GIF, or WebP and attach it again. Claude Code can verify dimensions for these formats without the image processor.
* If the message reports a dimension or size limit, resize or recompress the image below that limit before attaching.
@@ -614,7 +701,7 @@
PDF errors
-The PDF you attached could not be processed.
+The PDF you attached couldn’t be processed.
PDF too large (max 100 pages, 32 MB). Try splitting it or extracting text first.
PDF is password protected. Try removing protection or extracting text first.
@@ -637,7 +724,7 @@
API Error: 400 ... Extra inputs are not permitted ... tools.0.custom.input_examples
API Error: 400 ... Unexpected value(s) for the `anthropic-beta` header
-Claude Code sends beta-only fields such as `context_management`, `effort`, and tool `input_examples` alongside an `anthropic-beta` header that enables them. When a gateway forwards the body but drops the header, the API sees fields it does not recognize. **What to do:**
+Claude Code sends beta-only fields such as `context_management`, `effort`, and tool `input_examples` alongside an `anthropic-beta` header that enables them. When a gateway forwards the body but drops the header, the API sees fields it doesn’t recognize. **What to do:**
* Configure your gateway to forward the `anthropic-beta` header. See [feature pass-through](</docs/en/llm-gateway-protocol#feature-pass-through>) for what gateways must forward.
* As a fallback, set [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`](</docs/en/env-vars>) before launching. This disables features that require the beta header so requests succeed through a gateway that cannot forward it.
@@ -657,7 +744,7 @@
* **Interactive CLI** : run `/model` to pick from models available to your account.
* **Non-interactive mode (`-p`)**: pass `--model` with a valid alias or ID, or set [`ANTHROPIC_MODEL`](</docs/en/env-vars>). The error text shows `Run --model` on this surface.
* **Agent SDK** : the error text omits the hint because the model is set programmatically. Set [`model` on `Options`](</docs/en/agent-sdk/typescript#options>) in TypeScript or [`ClaudeAgentOptions(model=...)`](</docs/en/agent-sdk/python#claudeagentoptions>) in Python, and handle the structured `model_not_found` error to surface your own retry or model picker.
- * Use an alias such as `sonnet` or `opus` instead of a full versioned ID. Aliases resolve to a maintained default so they do not go stale. See [Model configuration](</docs/en/model-config>).
+ * Use an alias such as `sonnet` or `opus` instead of a full versioned ID. Aliases resolve to a maintained default so they don’t go stale. See [Model configuration](</docs/en/model-config>).
* If the wrong model keeps coming back in the CLI, a stale ID is set somewhere. Check in [priority order](</docs/en/model-config#setting-your-model>): the `--model` flag, the `ANTHROPIC_MODEL` environment variable, then the `model` field in `.claude/settings.local.json`, your project’s `.claude/settings.json`, and `~/.claude/settings.json`. Remove the stale value and Claude Code falls back to your account default.
* For Vertex AI deployments, see [Vertex AI troubleshooting](</docs/en/google-vertex-ai#troubleshooting>).
@@ -690,7 +777,7 @@
**What to do:**
* Run `/model` to pick from the models your organization allows. Restricted models are hidden from the picker.
- * If the restricted model was set in `--model`, `ANTHROPIC_MODEL`, or the `model` field of a settings file, remove or update that value so the notice does not recur on each launch
+ * If the restricted model was set in `--model`, `ANTHROPIC_MODEL`, or the `model` field of a settings file, remove or update that value so the notice doesn’t recur on each launch
* If you need access to the restricted model, ask your organization admin to enable it. See [Organization model restrictions](</docs/en/model-config#organization-model-restrictions>).
###
@@ -738,7 +825,7 @@
All three variants mean the same thing: the sequence of `tool_use`, `tool_result`, and `thinking` blocks in history no longer matches what the API expects. **What to do:**
- * If you are using Opus 4.7 or Opus 4.8, run `claude update` first. Versions before v2.1.156 can trigger this error during normal tool use, and `/rewind` does not clear it.
+ * If you are using Opus 4.7 or Opus 4.8, run `claude update` first. Versions before v2.1.156 can trigger this error during normal tool use, and `/rewind` doesn’t clear it.
* Run `/rewind`, or press Esc twice, to step back to a checkpoint before the corrupted turn and continue from there. See [Checkpointing](</docs/en/checkpointing>) for how checkpoints are created and restored.
###
@@ -754,16 +841,39 @@
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:**
* 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 cannot 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`.
+ * 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.
##
+Command-line errors
+
+These errors come from Claude Code’s own validation of the `claude` command line. Claude Code prints them immediately, before it creates a session or sends any API request.
+
+###
+
+
+
+Conflict between —bg and —print
+
+This message requires Claude Code v2.1.198 or later. You combined `--bg` with `-p` or `--print` in the same `claude` invocation. `--bg` starts a [background session](</docs/en/agent-view#from-your-shell>) that you later attach to with `claude agents`, while `--print` runs [non-interactively](</docs/en/headless>) and never starts the interactive session that `claude agents` attaches to. Before v2.1.198 this combination silently created a background job that could never be attached to.
+
+ --bg and --print conflict: --print never starts the interactive session that `claude agents` attaches to, so the job would be unattachable. The prompt is the positional — drop --print: `claude --bg '<task>'`.
+
+**What to do:**
+
+ * Drop `-p` or `--print`. `--bg` takes the prompt as its positional argument, so `claude --bg "<task>"` is the complete command. See [Dispatch new agents from your shell](</docs/en/agent-view#from-your-shell>).
+ * To run the prompt non-interactively and print the result instead of creating a background session, drop `--bg` and run `claude -p "<task>"`
+
+##
+
+
+
Responses seem lower quality than usual
-If Claude’s answers seem less capable than you expect but no error is shown, the cause is usually conversation state rather than the model itself. Claude Code does not silently change model versions. It can switch to a fallback model in three specific cases:
+If Claude’s answers seem less capable than you expect but no error is shown, the cause is usually conversation state rather than the model itself. Claude Code doesn’t silently change model versions. It can switch to a fallback model in three specific cases:
* A configured [`--fallback-model`](</docs/en/cli-reference#cli-flags>) takes over after an availability error, for that turn only, with a notice in the transcript
* A Bedrock or Vertex AI startup check finds your default model unavailable
@@ -784,7 +894,7 @@
Report an error
-This page covers errors from the Claude API. For errors from other Claude Code components, see the relevant guide:
+For errors from components this page doesn’t cover, see the relevant guide:
* MCP server failed to connect or authenticate: [MCP](</docs/en/mcp>)
* Hook script failed or blocked a tool: [Debug hooks](</docs/en/hooks#debug-hooks>)
--- a/feature-availability.md
+++ b/feature-availability.md
@@ -46,7 +46,7 @@
* [Remote Control](</docs/en/remote-control>)
* [Chrome extension](</docs/en/chrome>)
* [Computer use](</docs/en/computer-use>): Pro and Max plans
- * [Artifacts](</docs/en/artifacts>): Team and Enterprise plans
+ * [Artifacts](</docs/en/artifacts>): Pro, Max, Team, and Enterprise plans
* [Voice dictation](</docs/en/voice-dictation>)
Desktop is the partial exception: Enterprise deployments can route Desktop to Vertex AI or a gateway provider via [managed settings](<https://support.claude.com/en/articles/12622667-enterprise-configuration>), and the [Cowork on 3P research preview](<https://claude.com/docs/cowork/3p/overview>) runs the Code tab on Bedrock, Vertex AI, Foundry, or a self-hosted LLM gateway. For per-plan availability of these features, see Availability by subscription plan.
@@ -153,7 +153,7 @@
[Computer use](</docs/en/computer-use>)| ✓| ✓| ✗| ✗
Dispatch ([Desktop](</docs/en/desktop#sessions-from-dispatch>))| ✓| ✓| ✗| ✗
[Code Review](</docs/en/code-review>)| ✗| ✗| ✓| ✓
-[Artifacts](</docs/en/artifacts>)| ✗| ✗| ✓| Admin-enabled
+[Artifacts](</docs/en/artifacts>)| ✓| ✓| ✓| Admin-enabled
[Analytics dashboard, API, and contribution metrics](</docs/en/analytics>)| ✗| ✗| ✓| ✓
[Server-managed settings](</docs/en/server-managed-settings>)| ✗| ✗| ✓| ✓
[SSO](<https://support.claude.com/en/articles/9266767-what-is-the-team-plan>)| ✗| ✗| ✓| ✓
--- a/file-checkpointing.md
+++ b/file-checkpointing.md
@@ -36,7 +36,7 @@
Implement checkpointing
-To use file checkpointing, enable it in your options, capture checkpoint UUIDs from the response stream, then call `rewindFiles()` (TypeScript) or `rewind_files()` (Python) when you need to restore. The following example shows the complete flow: enable checkpointing, capture the checkpoint UUID and session ID from the response stream, then resume the session later to rewind files. Each step is explained in detail below.
+To use file checkpointing, enable it in your options, capture checkpoint UUIDs from the response stream, then call `rewindFiles()` (TypeScript) or `rewind_files()` (Python) when you need to restore. The following example shows the complete flow: enable checkpointing, capture the checkpoint UUID and session ID from the response stream, then resume the session later to rewind files. Each step is explained in detail below. The examples in this section use the prompt “Refactor the authentication module”. Run them in a project that contains an authentication module, or change the prompt to name files that exist in your project, so you can watch files change and see the rewind restore them.
Python
@@ -150,7 +150,7 @@
await client.rewind_files(checkpoint_id)
break
-If you capture the session ID and checkpoint ID, you can also rewind from the CLI:
+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:
claude -p --resume <session-id> --rewind-files <checkpoint-uuid>
--- a/fullscreen.md
+++ b/fullscreen.md
@@ -44,8 +44,8 @@
* **Click a suggestion in the`/` command or `@` file list** to accept it. Hovering highlights the row under your cursor.
* **Click an option in a select menu** to choose it. This covers permission prompts, `/model`, `/config`, and other dialogs that show a list of options. Hovering shows a pointer on the row under your cursor. Requires Claude Code v2.1.187 or later.
* **Click a collapsed tool result** to expand it and see the full output. Click again to collapse. The tool call and its result expand together. Only messages that have more to show are clickable.
- * **Hold`Cmd` on macOS, or `Ctrl` on Linux and Windows, and click a URL or file path** to open it. File paths in tool output, like the ones printed after an Edit or Write, open in your default application. Plain `http://` and `https://` URLs open in your browser. As of v2.1.181, a plain click without holding `Cmd` or `Ctrl` no longer opens links, matching native terminal behavior. In the VS Code integrated terminal and similar xterm.js-based terminals, Claude Code defers to the terminal’s own link handler, which uses the same gesture.
- * **Click and drag** to select text anywhere in the conversation. Double-click selects a word, matching iTerm2’s word boundaries so a file path selects as one unit. Triple-click selects the line.
+ * **Hold`Cmd` on macOS, or `Ctrl` on Linux and Windows, and click a URL or file path** to open it. File paths in tool output, like the ones printed after an Edit or Write, open in your default application. Plain `http://` and `https://` URLs open in your browser. As of v2.1.181, a plain click without holding `Cmd` or `Ctrl` no longer opens links, matching native terminal behavior. Some macOS terminals forward `Cmd`+click to the running app instead of opening the link themselves, and the terminal mouse protocol has no way to encode the `Cmd` key, so Claude Code receives it as a plain click. In Ghostty, and as of v2.1.198 in Warp on macOS, Claude Code detects this and lets a plain click on a link open it, and holding `Cmd` still works. In the VS Code integrated terminal and similar xterm.js-based terminals, Claude Code defers to the terminal’s own link handler, which uses the same gesture.
+ * **Click and drag** to select text anywhere in the conversation. Double-click selects a word, matching iTerm2’s word boundaries so a file path selects as one unit. As of v2.1.198, double-clicking a URL selects the whole URL, including the scheme. Triple-click selects the line.
* **Scroll with the mouse wheel** to move through the conversation.
Selected text copies to your clipboard automatically on mouse release. To turn this off, toggle Copy on select in `/config`. With Copy on select off, press `Ctrl+Shift+c` to copy manually. On terminals that support the kitty keyboard protocol, such as kitty, WezTerm, Ghostty, and iTerm2, `Cmd+c` also works. If you have a selection active, `Ctrl+c` copies instead of cancelling. With a selection active, hold `Shift` and press the arrow keys to extend it from the keyboard. `Shift+↑` and `Shift+↓` scroll the viewport when the selection reaches the top or bottom edge. `Shift+Home` and `Shift+End` extend to the start or end of the current line.
--- a/gateways.md
+++ b/gateways.md
@@ -32,7 +32,7 @@
Claude apps gateway
-Claude apps gateway is Anthropic’s self-hosted gateway, included in the `claude` binary. It routes to Amazon Bedrock, Google Cloud, Microsoft Foundry, or the Anthropic API as the upstream. Developers sign in with your corporate identity provider through `/login`, the gateway enforces model access and [managed settings](</docs/en/permissions#managed-settings>) by IdP group, and it emits [OpenTelemetry Protocol (OTLP)](</docs/en/monitoring-usage>) usage metrics to your own observability stack. Because it is built and tested alongside each Claude Code release, it forwards the headers and request fields Claude Code sends. A gateway maintained separately needs its [forwarding rules updated](</docs/en/llm-gateway-protocol#forward-as-open-lists>) as those headers and fields change with each release; Claude apps gateway releases with the CLI, so there is no list to keep current. See [Availability and limitations](</docs/en/claude-apps-gateway#availability-and-limitations>) for the small set of features that behave differently on a gateway session. The gateway sign-in is a browser SSO step, and there is no service-token flow, so a CI pipeline with no developer to approve the sign-in can’t authenticate through it; configure those against your provider directly. Agent SDK sessions and `claude -p` runs on a machine where a developer has signed in use that machine’s gateway session and are governed by its policies. See [CI pipelines and remote machines](</docs/en/claude-apps-gateway#ci-pipelines-and-remote-machines>). See [Claude apps gateway](</docs/en/claude-apps-gateway>) to deploy it.
+Claude apps gateway is Anthropic’s self-hosted gateway, included in the `claude` binary. It routes to Amazon Bedrock, Claude Platform on AWS, Google Cloud, Microsoft Foundry, or the Anthropic API as the upstream. Developers sign in with your corporate identity provider through `/login`, the gateway enforces model access and [managed settings](</docs/en/permissions#managed-settings>) by IdP group, and it emits [OpenTelemetry Protocol (OTLP)](</docs/en/monitoring-usage>) usage metrics to your own observability stack. Because it is built and tested alongside each Claude Code release, it forwards the headers and request fields Claude Code sends. A gateway maintained separately needs its [forwarding rules updated](</docs/en/llm-gateway-protocol#forward-as-open-lists>) as those headers and fields change with each release; Claude apps gateway releases with the CLI, so there is no list to keep current. See [Availability and limitations](</docs/en/claude-apps-gateway#availability-and-limitations>) for the small set of features that behave differently on a gateway session. The gateway sign-in is a browser SSO step, and there is no service-token flow, so a CI pipeline with no developer to approve the sign-in can’t authenticate through it; configure those against your provider directly. Agent SDK sessions and `claude -p` runs on a machine where a developer has signed in use that machine’s gateway session and are governed by its policies. See [CI pipelines and remote machines](</docs/en/claude-apps-gateway#ci-pipelines-and-remote-machines>). See [Claude apps gateway](</docs/en/claude-apps-gateway>) to deploy it.
###
Show diff (721 lines)
--- a/hooks.md
+++ b/hooks.md
@@ -8,7 +8,11 @@
Hook lifecycle
-Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Events fall into three cadences: once per session (`SessionStart`, `SessionEnd`), once per turn (`UserPromptSubmit`, `Stop`, `StopFailure`), and on every tool call inside the agentic loop (`PreToolUse`, `PostToolUse`):
+Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Events fall into three cadences:
+
+ * once per session: `SessionStart` and `SessionEnd`
+ * once per turn: `UserPromptSubmit`, `Stop`, and `StopFailure`
+ * on every tool call inside the agentic loop: `PreToolUse` and `PostToolUse`
The table below summarizes when each event fires. The Hook events section documents the full input schema and decision control options for each one.
@@ -184,7 +188,7 @@
Only letters, digits, `_`, `-`, spaces, `,`, and `|`| Exact string, or list of exact strings separated by `|` or `,` with optional surrounding whitespace| `Bash` matches only the Bash tool; `Edit|Write` and `Edit, Write` each match either tool exactly; `code-reviewer` matches only that agent type
Contains any other character| JavaScript regular expression, unanchored| `^Notebook` matches any tool whose name starts with `Notebook`; `mcp__memory__.*` matches every tool from the `memory` server
-A matcher on the regular-expression path is tested with JavaScript’s `RegExp.prototype.test`, which succeeds on a match anywhere in the value. `Edit.*` matches both `Edit` and `NotebookEdit`; wrap the pattern in `^` and `$`, as in `^Edit$`, when you need a whole-string match. Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression, so it also fires for `senior-code-reviewer`; anchor it as `^code-reviewer$` on those versions to match only that name. `FileChanged` and `StopFailure` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives. Every other event with matcher support in the table that follows accepts `|` or `,`. The `FileChanged` event does not follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
+A matcher on the regular-expression path is tested with JavaScript’s `RegExp.prototype.test`, which succeeds on a match anywhere in the value. `Edit.*` matches both `Edit` and `NotebookEdit`; wrap the pattern in `^` and `$`, as in `^Edit$`, when you need a whole-string match. Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression, so it also fires for `senior-code-reviewer`; anchor it as `^code-reviewer$` on those versions to match only that name. `FileChanged` and `StopFailure` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives. Every other event with matcher support in the table that follows accepts `|` or `,`. The `FileChanged` event doesn’t follow these rules when building its watch list. See FileChanged. Each event type matches on a different field:
Event| What the matcher filters| Example matcher values
---|---|---
@@ -192,7 +196,7 @@
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, custom agent names, or plugin-scoped names like `^my-plugin:reviewer$`
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
@@ -285,7 +289,7 @@
* **Prompt hooks** (`type: "prompt"`): send a prompt to a Claude model for single-turn evaluation. The model returns a yes/no decision as JSON. See Prompt-based hooks.
* **Agent hooks** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. Agent hooks are experimental and may change. See Agent-based hooks.
-All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string and `args`, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.
+All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string and `args`, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI. As of v2.1.199, [`$CLAUDE_CODE_BRIDGE_SESSION_ID`](</docs/en/env-vars>) is set to the [Remote Control](</docs/en/remote-control>) session ID while the local session has an active Remote Control connection.
####
@@ -313,7 +317,7 @@
`Bash(rm *)`| `echo $(date)`| no| no subcommand matches `rm *`
`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
-The filter also fails open, running your hook regardless of pattern, when the Bash command cannot be parsed. Because the `if` filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny.
+The filter also fails open, running your hook regardless of pattern, when the Bash command can’t be parsed. Because the `if` filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny.
####
@@ -335,7 +339,7 @@
A command hook runs as exec form when `args` is set, and shell form when `args` is omitted. Set `args` whenever the hook references a path placeholder, since each element is passed as one argument with no quoting. Omit `args` when you need shell features like pipes or `&&`, or when neither concern applies. **Exec form** runs when `args` is present. Claude Code resolves `command` as an executable on `PATH` and spawns it directly with `args` as the argument vector. There is no shell, so each `args` element is one argument exactly as written, and path placeholders like `${CLAUDE_PLUGIN_ROOT}` are substituted into `command` and into each `args` element as plain strings. Special characters such as apostrophes, `$`, and backticks pass through verbatim because there is no shell to interpret them. No shell tokenization happens on any platform. **Shell form** runs when `args` is absent. The `command` string is passed to a shell: `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed. Set the `shell` field to choose explicitly. The shell tokenizes the string, expands variables, and interprets pipes, `&&`, redirects, and globs.
-On Windows, exec form requires `command` to resolve to a real executable such as a `.exe`. The `.cmd` and `.bat` shims that npm, npx, eslint, and other tools install in `node_modules/.bin` are not executables and cannot be spawned without a shell. To run them in exec form, invoke the underlying script with `node` directly, for example `"command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/node_modules/eslint/bin/eslint.js"]`. The `node` plus script-path pattern works on every platform because `node.exe` is a real binary. To run a `.cmd` or `.bat` shim by name, use shell form.
+On Windows, exec form requires `command` to resolve to a real executable such as a `.exe`. The `.cmd` and `.bat` shims that npm, npx, eslint, and other tools install in `node_modules/.bin` are not executables and can’t be spawned without a shell. To run them in exec form, invoke the underlying script with `node` directly, for example `"command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/node_modules/eslint/bin/eslint.js"]`. The `node` plus script-path pattern works on every platform because `node.exe` is a real binary. To run a `.cmd` or `.bat` shim by name, use shell form.
This example runs a Node script bundled with a plugin. Exec form passes the resolved script path as one argument with no quoting:
@@ -354,7 +358,7 @@
Both forms support the same path placeholders, and both export them as the environment variables `CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, and `CLAUDE_PLUGIN_DATA` on the spawned process, so a script can read `process.env.CLAUDE_PLUGIN_ROOT` regardless of how it was launched. Plugin hooks additionally substitute `${user_config.*}` values; see [User configuration](</docs/en/plugins-reference#user-configuration>).
-In exec form, `command` is the executable name or path only. If `command` is a bare name with no path separator and contains whitespace alongside `args`, Claude Code logs a warning because the spawn will fail: there is no executable named `node script.js`. Move the extra tokens into `args`. Absolute paths with spaces, such as `C:\Program Files\nodejs\node.exe`, are a single valid executable and do not trigger the warning.
+In exec form, `command` is the executable name or path only. If `command` is a bare name with no path separator and contains whitespace alongside `args`, Claude Code logs a warning because the spawn will fail: there is no executable named `node script.js`. Move the extra tokens into `args`. Absolute paths with spaces, such as `C:\Program Files\nodejs\node.exe`, are a single valid executable and don’t trigger the warning.
####
@@ -544,7 +548,7 @@
Disable or remove hooks
-To remove a hook, delete its entry from the settings JSON file. To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration. The `disableAllHooks` setting respects the managed settings hierarchy. If an administrator has configured hooks through managed policy settings, `disableAllHooks` set in user, project, or local settings cannot disable those managed hooks. Only `disableAllHooks` set at the managed settings level can disable managed hooks. Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
+To remove a hook, delete its entry from the settings JSON file. To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration. The `disableAllHooks` setting respects the managed settings hierarchy. If an administrator has configured hooks through managed policy settings, `disableAllHooks` set in user, project, or local settings can’t disable those managed hooks. Only `disableAllHooks` set at the managed settings level can disable managed hooks. Direct edits to hooks in settings files are normally picked up automatically by the file watcher.
##
@@ -552,7 +556,7 @@
Hook input and output
-Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event’s section under Hook events includes its specific input schema and decision control options. On macOS and Linux, command hooks run in their own session without a controlling terminal as of v2.1.139. The hook process and any child processes cannot open `/dev/tty` or send escape sequences directly to the Claude Code interface. Windows has no `/dev/tty`. To surface a message to the user on any platform, return `systemMessage` in JSON output. To trigger a desktop notification, set a window title, or ring the bell, return `terminalSequence` instead.
+Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event’s section under Hook events includes its specific input schema and decision control options. On macOS and Linux, command hooks run in their own session without a controlling terminal as of v2.1.139. The hook process and any child processes can’t open `/dev/tty` or send escape sequences directly to the Claude Code interface. Windows has no `/dev/tty`. To surface a message to the user on any platform, return `systemMessage` in JSON output. To trigger a desktop notification, set a window title, or ring the bell, return `terminalSequence` instead.
###
@@ -579,7 +583,7 @@
`agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls.
`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. For subagents shipped by a [plugin](</docs/en/plugins>), this is the plugin-scoped identifier such as `my-plugin:reviewer`, not the bare frontmatter name. See SubagentStart for how to write a matcher against a plugin-scoped name.
-Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value does not change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
+Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value doesn’t change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin:
{
"session_id": "abc123",
@@ -633,15 +637,15 @@
`UserPromptExpansion`| Yes| Blocks the expansion
`Stop`| Yes| Prevents Claude from stopping, continues the conversation
`SubagentStop`| Yes| Prevents the subagent from stopping
-`TeammateIdle`| Yes| Prevents the teammate from going idle (teammate continues working)
+`TeammateIdle`| Yes| Prevents the teammate from going idle, so it continues working
`TaskCreated`| Yes| Rolls back the task creation
`TaskCompleted`| Yes| Prevents the task from being marked as completed
`ConfigChange`| Yes| Blocks the configuration change from taking effect (except `policy_settings`)
`StopFailure`| No| Output and exit code are ignored
-`PostToolUse`| No| Shows stderr to Claude (tool already ran)
-`PostToolUseFailure`| No| Shows stderr to Claude (tool already failed)
+`PostToolUse`| No| Shows stderr to Claude; the tool already ran
+`PostToolUseFailure`| No| Shows stderr to Claude; the tool already failed
`PostToolBatch`| Yes| Stops the agentic loop before the next model call
-`PermissionDenied`| No| Exit code and stderr are ignored (denial already occurred). Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry
+`PermissionDenied`| No| Exit code and stderr are ignored because the denial already occurred. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry
`Notification`| No| Shows stderr to user only
`SubagentStart`| No| Shows stderr to user only
`SessionStart`| No| Shows stderr to user only
@@ -658,6 +662,8 @@
`InstructionsLoaded`| No| Exit code is ignored
`MessageDisplay`| No| The original text is displayed
+For `SessionStart`, `Setup`, and `SubagentStart`, the exit code 2 stderr renders in the transcript as a `<hook name> hook error` notice, the same way a non-blocking error does. Claude doesn’t see it, and the session or subagent proceeds. For `SubagentStart`, the notice appears in the subagent’s own transcript, not in the parent conversation. As of Claude Code v2.1.199, `SessionStart`, `Setup`, and `SubagentStart` show exit code 2 stderr in the transcript. Earlier versions wrote it to the debug log only.
+
###
@@ -672,7 +678,7 @@
* **Non-2xx status** : non-blocking error, execution continues
* **Connection failure or timeout** : non-blocking error, execution continues
-Unlike command hooks, HTTP hooks cannot signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields.
+Unlike command hooks, HTTP hooks can’t signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields.
###
@@ -728,7 +734,7 @@
The `{ "terminalSequence": "..." }` shape is the same from any shell or language. On Windows, build the escape string in PowerShell or a script and emit the same JSON object.
-`terminalSequence` is the supported replacement for hooks that previously wrote escape sequences directly to `/dev/tty`. The allowlist is restricted to sequences that cannot move the cursor or alter colors, so a hook can never corrupt an on-screen prompt.
+`terminalSequence` is the supported replacement for hooks that previously wrote escape sequences directly to `/dev/tty`. The allowlist is restricted to sequences that can’t move the cursor or alter colors, so a hook can never corrupt an on-screen prompt.
####
@@ -736,7 +742,7 @@
Add context for Claude
-The `additionalContext` field passes a string from your hook into Claude’s context window. Claude Code wraps the string in a system reminder and inserts it into the conversation at the point where the hook fired. Claude reads the reminder on the next model request, but it does not appear as a chat message in the interface. Return `additionalContext` inside `hookSpecificOutput` alongside the event name:
+The `additionalContext` field passes a string from your hook into Claude’s context window. Claude Code wraps the string in a system reminder and inserts it into the conversation at the point where the hook fired. Claude reads the reminder on the next model request, but it doesn’t appear as a chat message in the interface. Return `additionalContext` inside `hookSpecificOutput` alongside the event name:
{
"hookSpecificOutput": {
@@ -787,7 +793,7 @@
* `PreToolUse`: `updatedInput` directly under `hookSpecificOutput` replaces a tool’s arguments before it runs. See PreToolUse decision control
* `PermissionRequest`: `updatedInput` inside the `decision` object. See PermissionRequest decision control
* `PostToolUse`: `updatedToolOutput` replaces the tool’s result. See PostToolUse decision control
- * `UserPromptSubmit`: cannot replace the prompt; it only injects `additionalContext` alongside it
+ * `UserPromptSubmit`: can’t replace the prompt; it only injects `additionalContext` alongside it
For redaction or transformation use cases, intercept at `PreToolUse` for outbound tool inputs and `PostToolUse` for inbound tool results. Here are examples of each pattern in action:
@@ -844,7 +850,7 @@
SessionStart
-Runs when Claude Code starts a new session or resumes an existing session. Useful for loading development context like existing issues or recent changes to your codebase, or setting up environment variables. For static context that does not require a script, use [CLAUDE.md](</docs/en/memory>) instead. SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` and `type: "mcp_tool"` hooks are supported. The matcher value corresponds to how the session was initiated:
+Runs when Claude Code starts a new session or resumes an existing session. Useful for loading development context like existing issues or recent changes to your codebase, or setting up environment variables. For static context that doesn’t require a script, use [CLAUDE.md](</docs/en/memory>) instead. SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` and `type: "mcp_tool"` hooks are supported. The matcher value corresponds to how the session was initiated:
Matcher| When it fires
---|---
@@ -859,7 +865,14 @@
SessionStart input
-In addition to the common input fields, SessionStart hooks receive `source` and optionally `model`, `agent_type`, and `session_title`. The `source` field indicates how the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, or `"compact"` after compaction. The `model` field contains the active model identifier. It can be omitted, for example after `/clear` or when a session is restored through conversation recovery, so check for the field before reading it. If you start Claude Code with `claude --agent <name>`, an `agent_type` field contains the agent name. The `session_title` field carries the current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly.
+In addition to the common input fields, SessionStart hooks receive `source` and optionally `model`, `agent_type`, and `session_title`:
+
+Field| Description
+---|---
+`source`| How the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, or `"compact"` after compaction
+`model`| The active model identifier. It can be omitted, for example after `/clear` or when a session is restored through conversation recovery, so check for the field before reading it
+`agent_type`| The agent name, present when you start Claude Code with `claude --agent <name>`
+`session_title`| The current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly
{
"session_id": "abc123",
@@ -881,7 +894,7 @@
Field| Description
---|---
`additionalContext`| String added to Claude’s context at the start of the conversation, before the first prompt. See Add context for Claude for how the text is delivered and what to put in it
-`initialUserMessage`| String used as the first user message of the session. Applies in [non-interactive mode](</docs/en/headless>) (`-p`), where it becomes the first turn even if no prompt is provided. If a prompt is provided, it follows as the next turn. Unlike `additionalContext`, which attaches to an existing turn, this creates the turn
+`initialUserMessage`| String used as the first user message of the session. Applies in [non-interactive mode](</docs/en/headless>) with the `-p` flag, where it becomes the first turn even if no prompt is provided. If a prompt is provided, it follows as the next turn. Unlike `additionalContext`, which attaches to an existing turn, this creates the turn
`sessionTitle`| Sets the session title, with the same effect as `/rename`. Use to name sessions automatically from the launch folder, git branch, or worktree name. Applies only when `source` is `"startup"` or `"resume"`; ignored on `"clear"` and `"compact"`
`watchPaths`| Array of absolute paths to watch for FileChanged events during this session
`reloadSkills`| Boolean. When `true`, Claude Code re-scans the [skill](</docs/en/skills>) and command directories after the SessionStart hooks complete, so skills the hook installed are available in the same session, starting with the first prompt
@@ -940,7 +953,7 @@
Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.
-`CLAUDE_ENV_FILE` is available for SessionStart, Setup, CwdChanged, and FileChanged hooks. Other hook types do not have access to this variable.
+`CLAUDE_ENV_FILE` is available for SessionStart, Setup, CwdChanged, and FileChanged hooks. Other hook types don’t have access to this variable.
###
@@ -948,14 +961,14 @@
Setup
-Fires only when you launch Claude Code with `--init-only`, or with `--init` or `--maintenance` in print mode (`-p`). It does not fire on normal startup. Use it for one-time dependency installation or scheduled cleanup that you trigger explicitly from CI or scripts, separate from normal session startup. For per-session initialization, use SessionStart instead. The matcher value corresponds to the CLI flag that triggered the hook:
+Fires only when you launch Claude Code with `--init-only`, or with `--init` or `--maintenance` in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It doesn’t fire on normal startup. Use it for one-time dependency installation or scheduled cleanup that you trigger explicitly from CI or scripts, separate from normal session startup. For per-session initialization, use SessionStart instead. The matcher value corresponds to the CLI flag that triggered the hook:
Matcher| When it fires
---|---
`init`| `claude --init-only` or `claude -p --init`
`maintenance`| `claude -p --maintenance`
-`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p` (print mode); in an interactive session those two flags do not currently fire Setup hooks. Because Setup does not fire on every launch, a plugin that needs a dependency installed cannot rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
+`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p`; in an interactive session those two flags don’t currently fire Setup hooks. Because Setup doesn’t fire on every launch, a plugin that needs a dependency installed can’t rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies.
####
@@ -979,7 +992,7 @@
Setup decision control
-Setup hooks cannot block. On exit code 2, stderr is shown to the user; on any other non-zero exit code, stderr appears only when you launch with `--verbose`. In both cases execution continues. To pass information into Claude’s context, return `additionalContext` in JSON output; plain stdout is written to the debug log only. In addition to the JSON output fields available to all hooks, you can return these event-specific fields:
+Setup hooks can’t block. Any non-zero exit code, including 2, surfaces stderr to the user as a `<hook name> hook error` notice, and execution continues. In [non-interactive mode](</docs/en/headless>), hook output appears only when you launch with `--verbose`. To pass information into Claude’s context, return `additionalContext` in JSON output; plain stdout is written to the debug log only. In addition to the JSON output fields available to all hooks, you can return these event-specific fields:
Field| Description
---|---
@@ -1000,7 +1013,7 @@
InstructionsLoaded
-Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook does not support blocking or decision control. It runs asynchronously for observability purposes. The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads.
+Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook doesn’t support blocking or decision control. It runs asynchronously for observability purposes. The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads.
####
@@ -1035,7 +1048,7 @@
InstructionsLoaded decision control
-InstructionsLoaded hooks have no decision control. They cannot block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
+InstructionsLoaded hooks have no decision control. They can’t block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.
###
@@ -1073,7 +1086,7 @@
* **Plain text stdout** : any non-JSON text written to stdout is added as context
* **JSON with`additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context
-Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely. To block a prompt, return a JSON object with `decision` set to `"block"`:
+Plain stdout is shown as hook output in the transcript. The `additionalContext` value is injected as a system reminder that Claude reads without a visible transcript entry. To block a prompt, return a JSON object with `decision` set to `"block"`:
Field| Description
---|---
@@ -1093,15 +1106,13 @@
}
}
-The JSON format isn’t required for simple use cases. To add context, you can print plain text to stdout with exit code 0. Use JSON when you need to block prompts or want more structured control.
-
###
UserPromptExpansion
-Runs when a user-typed slash command expands into a prompt before reaching Claude. Use this to block specific commands from direct invocation, inject context for a particular skill, or log which commands users invoke. For example, a hook matching `deploy` can block `/deploy` unless an approval file is present, or a hook matching a review skill can append the team’s review checklist as `additionalContext`. This event covers the path `PreToolUse` does not: a `PreToolUse` hook matching the `Skill` tool fires only when Claude calls the tool, but typing `/skillname` directly bypasses `PreToolUse`. `UserPromptExpansion` fires on that direct path. Matches on `command_name`. Leave the matcher empty to fire on every prompt-type slash command.
+Runs when a user-typed command expands into a prompt before reaching Claude. Use this to block specific commands from direct invocation, inject context for a particular skill, or log which commands users invoke. For example, a hook matching `deploy` can block `/deploy` unless an approval file is present, or a hook matching a review skill can append the team’s review checklist as `additionalContext`. This event covers the path `PreToolUse` doesn’t: a `PreToolUse` hook matching the `Skill` tool fires only when Claude calls the tool, but typing `/skillname` directly bypasses `PreToolUse`. `UserPromptExpansion` fires on that direct path. Matches on `command_name`. Leave the matcher empty to fire on every prompt-type command.
####
@@ -1134,7 +1145,7 @@
Field| Description
---|---
-`decision`| `"block"` prevents the slash command from expanding. Omit to allow it to proceed
+`decision`| `"block"` prevents the command from expanding. Omit to allow it to proceed
`reason`| Shown to the user when `decision` is `"block"`
`additionalContext`| String added to Claude’s context alongside the expanded prompt. See Add context for Claude
@@ -1159,7 +1170,7 @@
* transform the text an Agent SDK application shows its users
* redact API keys or internal hostnames from Claude’s responses
-Claude Code holds each batch until your hook returns, so keep the hook fast. If the hook fails or times out, Claude Code displays the original text. The default timeout for this event is 10 seconds; if your hook needs more time, set the `timeout` field in the hook entry. MessageDisplay is display-only: the replacement text changes only what is rendered on screen. The transcript and what Claude sees keep the original text, so Claude never sees the replacement, and verbose mode shows the original. The hook receives assistant message text only, so tool results and the text you type render unchanged. MessageDisplay does not support matchers and fires for every assistant message that streams text; messages with no text, such as tool-call-only responses, do not trigger it. In non-interactive runs, including Agent SDK queries and `claude -p`, MessageDisplay runs once per assistant message instead of once per batch of lines. The single call arrives after the message completes and carries the full message text: `index` is `0`, `final` is `true`, and `delta` holds the entire message. A hook that collects the `delta` text for each message receives the same total text in both modes.
+Claude Code holds each batch until your hook returns, so keep the hook fast. If the hook fails or times out, Claude Code displays the original text. The default timeout for this event is 10 seconds; if your hook needs more time, set the `timeout` field in the hook entry. MessageDisplay is display-only: the replacement text changes only what is rendered on screen. The transcript and what Claude sees keep the original text, so Claude never sees the replacement, and verbose mode shows the original. The hook receives assistant message text only, so tool results and the text you type render unchanged. MessageDisplay doesn’t support matchers and fires for every assistant message that streams text; messages with no text, such as tool-call-only responses, don’t trigger it. In non-interactive runs, including Agent SDK queries and `claude -p`, MessageDisplay runs once per assistant message instead of once per batch of lines. The single call arrives after the message completes and carries the full message text: `index` is `0`, `final` is `true`, and `delta` holds the entire message. A hook that collects the `delta` text for each message receives the same total text in both modes.
####
@@ -1172,7 +1183,7 @@
Field| Description
---|---
`turn_id`| UUID of the current turn
-`message_id`| UUID of the assistant message being displayed. Stable across every batch of the same message. This is not the API `msg_…` id, so it cannot be correlated with transcript message ids
+`message_id`| UUID of the assistant message being displayed. Stable across every batch of the same message. This is not the API `msg_…` id, so it can’t be correlated with transcript message ids
`index`| Zero-based index of this batch within the message
`final`| `true` on the message’s last batch. Each message has exactly one final batch
`delta`| The newly completed lines since the prior batch, terminating newlines included. Always whole lines, except the final batch which may end mid-line. In interactive runs, the final batch’s delta is empty when the message ends on a newline, so treat `final`, not a non-empty delta, as the end-of-message signal. In Agent SDK and `claude -p` runs, the single call carries the entire message
@@ -1201,7 +1212,7 @@
---|---
`displayContent`| Text displayed in place of the delta. Omit it to display the original
-MessageDisplay hooks have no decision control. They cannot block the message or change what is stored in the transcript or sent to Claude. This example strips markdown formatting from Claude’s responses for a plain-text display. The script reads each batch from stdin, removes bold markers and inline code backticks from `delta`, and returns the result as `displayContent`.
+MessageDisplay hooks have no decision control. They can’t block the message or change what is stored in the transcript or sent to Claude. This example strips markdown formatting from Claude’s responses for a plain-text display. The script reads each batch from stdin, removes bold markers and inline code backticks from `delta`, and returns the result as `displayContent`.
* macOS/Linux
@@ -1386,7 +1397,7 @@
Field| Type| Example| Description
---|---|---|---
-`status`| string| `"completed"`| `"completed"` for synchronous calls, `"async_launched"` for `run_in_background: true`
+`status`| string| `"completed"`| `"completed"` for foreground subagents, `"async_launched"` for background subagents. As of v2.1.198, subagents run in the background by default, so an omitted `run_in_background` also produces `"async_launched"`
`agentId`| string| `"a4d2c8f1e0b3a297"`| Identifier for the subagent run
`content`| array| `[{"type": "text", "text": "Found 12 endpoints..."}]`| The subagent’s final text blocks
`resolvedModel`| string| `"claude-sonnet-4-5"`| Model the subagent ran on, which may differ from the requested model. Requires Claude Code v2.1.174 or later
@@ -1395,7 +1406,7 @@
`totalToolUseCount`| number| `7`| Count of tool calls the subagent made
`usage`| object| `{"input_tokens": 8320, ...}`| Per-type token breakdown: `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`
-For `run_in_background: true` calls, the tool returns immediately after launching the subagent, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. The `resolvedModel` field names the model the subagent actually runs on, which can differ from the `model` value in `tool_input`, such as when `availableModels` or another override applies. It requires Claude Code v2.1.174 or later.
+For background subagents, the tool returns immediately after launching, so `tool_response` carries no usage fields. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. The `resolvedModel` field names the model the subagent actually runs on, which can differ from the `model` value in `tool_input`, such as when `availableModels` or another override applies. It requires Claude Code v2.1.174 or later.
##### AskUserQuestion
@@ -1404,7 +1415,7 @@
Field| Type| Example| Description
---|---|---|---
`questions`| array| `[{"question": "Which framework?", "header": "Framework", "options": [{"label": "React"}], "multiSelect": false}]`| Questions to present, each with a `question` string, short `header`, `options` array, and optional `multiSelect` flag
-`answers`| object| `{"Which framework?": "React"}`| Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude does not set this field; supply it via `updatedInput` to answer programmatically
+`answers`| object| `{"Which framework?": "React"}`| Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude doesn’t set this field; supply it via `updatedInput` to answer programmatically
##### ExitPlanMode
@@ -1428,7 +1439,7 @@
Field| Description
---|---
-`permissionDecision`| `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns
+`permissionDecision`| `"allow"` skips the permission prompt, except for tools that require user interaction. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns
`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored
`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored
`additionalContext`| String added to Claude’s context alongside the tool result. Ignored when `permissionDecision` is `"defer"`. See Add context for Claude
@@ -1447,7 +1458,7 @@
}
}
-`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer.
+`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer. As of v2.1.199, an MCP tool whose server marks it with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) is stricter: a hook can’t skip its approval prompt with `"allow"`, with or without `updatedInput`, because Claude Code can’t confirm the hook collected the interaction the tool needs.
PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format.
@@ -1459,12 +1470,12 @@
`"defer"` is for integrations that run `claude -p` as a subprocess and read its JSON output, such as an Agent SDK app or a custom UI built on top of Claude Code. It lets that calling process pause Claude at a tool call, collect input through its own interface, and resume where it left off. Claude Code honors this value only in [non-interactive mode](</docs/en/headless>) with the `-p` flag. In interactive sessions it logs a warning and ignores the hook result.
-The `defer` value requires Claude Code v2.1.89 or later. Earlier versions do not recognize it and the tool proceeds through the normal permission flow.
+The `defer` value requires Claude Code v2.1.89 or later. Earlier versions don’t recognize it and the tool proceeds through the normal permission flow.
The `AskUserQuestion` tool is the typical case: Claude wants to ask the user something, but there is no terminal to answer in. The round trip works like this:
1. Claude calls `AskUserQuestion`. The `PreToolUse` hook fires.
- 2. The hook returns `permissionDecision: "defer"`. The tool does not execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript.
+ 2. The hook returns `permissionDecision: "defer"`. The tool doesn’t execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript.
3. The calling process reads `deferred_tool_use` from the SDK result, surfaces the question in its own UI, and waits for an answer.
4. The calling process runs `claude -p --resume <session-id>`. The same tool call fires `PreToolUse` again.
5. The hook returns `permissionDecision: "allow"` with the answer in `updatedInput`. The tool executes and Claude continues.
@@ -1485,7 +1496,7 @@
There is no timeout or retry limit. The session remains on disk until you resume it, subject to the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) retention sweep that deletes session files after 30 days by default. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook. `"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved. If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.
-`--resume` restores the permission mode that was active when the tool was deferred, so you do not need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over. Passing `--permission-mode` explicitly on resume overrides the restored value.
+`--resume` restores the permission mode that was active when the tool was deferred, so you don’t need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over. Passing `--permission-mode` explicitly on resume overrides the restored value.
###
@@ -1534,7 +1545,7 @@
Field| Description
---|---
-`behavior`| `"allow"` grants the permission, `"deny"` denies it. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated, so a hook returning `"allow"` does not override a matching deny rule
+`behavior`| `"allow"` grants the permission, `"deny"` denies it. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated, so a hook returning `"allow"` doesn’t override a matching deny rule
`updatedInput`| For `"allow"` only: modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. The modified input is re-evaluated against deny and ask rules
`updatedPermissions`| For `"allow"` only: array of permission update entries to apply, such as adding an allow rule or changing the session permission mode
`message`| For `"deny"` only: tells Claude why the permission was denied
@@ -1652,7 +1663,7 @@
}
}
-`updatedToolOutput` only changes what Claude sees. The tool has already run by the time the hook fires, so any files written, commands executed, or network requests sent have already taken effect. Telemetry such as OpenTelemetry tool spans and analytics events also captures the original output before the hook runs. To prevent or modify a tool call before it runs, use a PreToolUse hook instead.The replacement value must match the tool’s output shape. Built-in tools return structured objects rather than plain strings. For example, `Bash` returns an object with `stdout`, `stderr`, `interrupted`, and `isImage` fields. For built-in tools, a value that does not match the tool’s output schema is ignored and the original output is used. MCP tool output is passed through without schema validation. Stripping error details that Claude needs can cause it to proceed on a false assumption.
+`updatedToolOutput` only changes what Claude sees. The tool has already run by the time the hook fires, so any files written, commands executed, or network requests sent have already taken effect. Telemetry such as OpenTelemetry tool spans and analytics events also captures the original output before the hook runs. To prevent or modify a tool call before it runs, use a PreToolUse hook instead.The replacement value must match the tool’s output shape. Built-in tools return structured objects rather than plain strings. For example, `Bash` returns an object with `stdout`, `stderr`, `interrupted`, and `isImage` fields. For built-in tools, a value that doesn’t match the tool’s output schema is ignored and the original output is used. MCP tool output is passed through without schema validation. Stripping error details that Claude needs can cause it to proceed on a false assumption.
###
@@ -1781,7 +1792,7 @@
PermissionDenied
-Runs when the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier denies a tool call. This hook only fires in auto mode: it does not run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call. Matches on tool name, same values as PreToolUse.
+Runs when the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier denies a tool call. This hook only fires in auto mode: it doesn’t run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call. Matches on tool name, same values as PreToolUse.
####
@@ -1825,7 +1836,7 @@
}
}
-When `retry` is `true`, Claude Code adds a message to the conversation telling the model it may retry the tool call. The denial itself is not reversed. If your hook does not return JSON, or returns `retry: false`, the denial stands and the model receives the original rejection message.
+When `retry` is `true`, Claude Code adds a message to the conversation telling the model it may retry the tool call. The denial itself is not reversed. If your hook doesn’t return JSON, or returns `retry: false`, the denial stands and the model receives the original rejection message.
###
@@ -1833,7 +1844,20 @@
Notification
-Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`. Omit the matcher to run hooks for all notification types. Use separate matchers to run different handlers depending on the notification type. This configuration triggers a permission-specific alert script when Claude needs permission approval and a different notification when Claude has been idle:
+Runs when Claude Code sends notifications. Matches on notification type. Omit the matcher to run hooks for all notification types.
+
+Matcher| When it fires
+---|---
+`permission_prompt`| Claude needs you to approve a tool use
+`idle_prompt`| Claude is done and waiting for your next prompt
+`auth_success`| Authentication completes
+`elicitation_dialog`| An MCP server opens an elicitation form
+`elicitation_complete`| An MCP elicitation form is submitted or dismissed
+`elicitation_response`| An MCP elicitation response is sent back to the server
+`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open in a terminal
+`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open in a terminal
+
+The `agent_needs_input` and `agent_completed` types require Claude Code v2.1.198 or later. Use separate matchers to run different handlers depending on the notification type. This configuration triggers a permission-specific alert script when Claude needs permission approval and a different notification when Claude has been idle:
{
"hooks": {
@@ -1878,7 +1902,7 @@
"notification_type": "permission_prompt"
}
-Notification hooks cannot block or modify notifications. They are intended for side effects such as forwarding the notification to an external service. The common JSON output fields such as `systemMessage` apply.
+Notification hooks can’t block or modify notifications. They are intended for side effects such as forwarding the notification to an external service. The common JSON output fields such as `systemMessage` apply.
###
@@ -1894,7 +1918,7 @@
SubagentStart input
-In addition to the common input fields, SubagentStart hooks receive `agent_id` with the unique identifier for the subagent and `agent_type` with the agent name (built-in agents like `"general-purpose"`, `"Explore"`, `"Plan"`, or custom agent names).
+In addition to the common input fields, SubagentStart hooks receive `agent_id` with the unique identifier for the subagent and `agent_type` with the agent name that the matcher filters on.
{
"session_id": "abc123",
@@ -1905,7 +1929,7 @@
"agent_type": "Explore"
}
-SubagentStart hooks cannot block subagent creation, but they can inject context into the subagent. In addition to the JSON output fields available to all hooks, you can return:
+SubagentStart hooks can’t block subagent creation, but they can inject context into the subagent. In addition to the JSON output fields available to all hooks, you can return:
Field| Description
---|---
@@ -1957,7 +1981,7 @@
TaskCreated
-Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created. When a `TaskCreated` hook exits with code 2, the task is not created and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCreated hooks do not support matchers and fire on every occurrence.
+Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created. When a `TaskCreated` hook exits with code 2, the task is not created and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCreated hooks don’t support matchers and fire on every occurrence.
####
@@ -2018,7 +2042,7 @@
TaskCompleted
-Runs when a task is being marked as completed. This fires in two situations: when any agent explicitly marks a task as completed through the TaskUpdate tool, or when an [agent team](</docs/en/agent-teams>) teammate finishes its turn with in-progress tasks. Use this to enforce completion criteria like passing tests or lint checks before a task can close. When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCompleted hooks do not support matchers and fire on every occurrence.
+Runs when a task is being marked as completed. This fires in two situations: when any agent explicitly marks a task as completed through the TaskUpdate tool, or when an [agent team](</docs/en/agent-teams>) teammate finishes its turn with in-progress tasks. Use this to enforce completion criteria like passing tests or lint checks before a task can close. When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCompleted hooks don’t support matchers and fire on every occurrence.
####
@@ -2176,7 +2200,7 @@
StopFailure
-Runs instead of Stop when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude cannot complete a response due to rate limits, authentication problems, or other API errors.
+Runs instead of Stop when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude can’t complete a response due to rate limits, authentication problems, or other API errors.
####
@@ -2210,7 +2234,7 @@
TeammateIdle
-Runs when an [agent team](</docs/en/agent-teams>) teammate is about to go idle after finishing its turn. Use this to enforce quality gates before a teammate stops working, such as requiring passing lint checks or verifying that output files exist. When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.
+Runs when an [agent team](</docs/en/agent-teams>) teammate is about to go idle after finishing its turn. Use this to enforce quality gates before a teammate stops working, such as requiring passing lint checks or verifying that output files exist. When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks don’t support matchers and fire on every occurrence.
####
@@ -2326,7 +2350,7 @@
"reason": "Configuration changes to project settings require admin approval"
}
-`policy_settings` changes cannot be blocked. Hooks still fire for `policy_settings` sources, so you can use them for audit logging, but any blocking decision is ignored. This ensures enterprise-managed settings always take effect.
+`policy_settings` changes can’t be blocked. Hooks still fire for `policy_settings` sources, so you can use them for audit logging, but any blocking decision is ignored. This ensures enterprise-managed settings always take effect.
###
@@ -2334,7 +2358,7 @@
CwdChanged
-Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with FileChanged for tools like [direnv](<https://direnv.net/>) that manage per-directory environment. CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. CwdChanged does not support matchers and fires on every directory change.
+Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with FileChanged for tools like [direnv](<https://direnv.net/>) that manage per-directory environment. CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. CwdChanged doesn’t support matchers and fires on every directory change.
####
@@ -2363,9 +2387,9 @@
Field| Description
---|---
-`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Returning an empty array clears the dynamic list, which is typical when entering a new directory
-
-CwdChanged hooks have no decision control. They cannot block the directory change.
+`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list. Paths from your `matcher` configuration are always watched. Returning an empty array clears the dynamic list, which is typical when entering a new directory
+
+CwdChanged hooks have no decision control. They can’t block the directory change.
###
@@ -2391,7 +2415,7 @@
Field| Description
---|---
`file_path`| Absolute path to the file that changed
-`event`| What happened: `"change"` (file modified), `"add"` (file created), or `"unlink"` (file deleted)
+`event`| What happened: `"change"` for a modified file, `"add"` for a created file, or `"unlink"` for a deleted file
{
"session_id": "abc123",
@@ -2412,9 +2436,9 @@
Field| Description
---|---
-`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Use this when your hook script discovers additional files to watch based on the changed file
-
-FileChanged hooks have no decision control. They cannot block the file change from occurring.
+`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list. Paths from your `matcher` configuration are always watched. Use this when your hook script discovers additional files to watch based on the changed file
+
+FileChanged hooks have no decision control. They can’t block the file change from occurring.
###
@@ -2422,7 +2446,7 @@
WorktreeCreate
-When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](</docs/en/sub-agents#choose-the-subagent-scope>), Claude Code creates an isolated working copy using `git worktree`. If you configure a WorktreeCreate hook, it replaces the default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
+Runs when a worktree is being created, either from `claude --worktree` or from a [subagent using `isolation: "worktree"`](</docs/en/sub-agents#choose-the-subagent-scope>). By default Claude Code creates the isolated working copy with `git worktree`. Configuring a WorktreeCreate hook replaces that default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:
{
"hooks": {
@@ -2447,7 +2471,7 @@
WorktreeCreate input
-In addition to the common input fields, WorktreeCreate hooks receive the `name` field. This is a slug identifier for the new worktree, either specified by the user or auto-generated (for example, `bold-oak-a3f2`).
+In addition to the common input fields, WorktreeCreate hooks receive the `name` field. This is a slug identifier for the new worktree, either specified by the user or auto-generated, for example `bold-oak-a3f2`.
{
"session_id": "abc123",
@@ -2463,7 +2487,7 @@
WorktreeCreate output
-WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook’s success or failure determines the outcome. The hook must return the absolute path to the created worktree directory:
+WorktreeCreate hooks don’t use the standard allow/block decision model. Instead, the hook’s success or failure determines the outcome. The hook must return the absolute path to the created worktree directory:
* **Command hooks** (`type: "command"`): print the path on stdout.
* **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body.
@@ -2476,7 +2500,7 @@
WorktreeRemove
-The cleanup counterpart to WorktreeCreate. This hook fires when a worktree is being removed, either when you exit a `--worktree` session and choose to remove it, or when a subagent with `isolation: "worktree"` finishes. For git-based worktrees, Claude handles cleanup automatically with `git worktree remove`. If you configured a WorktreeCreate hook for a non-git version control system, pair it with a WorktreeRemove hook to handle cleanup. Without one, the worktree directory is left on disk. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
+Runs when a worktree is being removed, either when you exit a `--worktree` session and choose to remove it, or when a subagent with `isolation: "worktree"` finishes. This is the cleanup counterpart to WorktreeCreate. For git-based worktrees, Claude Code handles cleanup automatically with `git worktree remove`. If you configured a WorktreeCreate hook for a non-git version control system, pair it with a WorktreeRemove hook to handle cleanup. Without one, the worktree directory is left on disk. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:
{
"hooks": {
@@ -2509,7 +2533,7 @@
"worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"
}
-WorktreeRemove hooks have no decision control. They cannot block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only.
+WorktreeRemove hooks have no decision control. They can’t block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only.
###
@@ -2573,7 +2597,7 @@
"compact_summary": "Summary of the compacted conversation..."
}
-PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.
+PostCompact hooks have no decision control. They can’t affect the compaction result but can perform follow-up tasks.
###
@@ -2608,7 +2632,7 @@
"reason": "other"
}
-SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If a hook needs more time, set a per-hook `timeout` in the hook configuration. The overall budget is automatically raised to the highest per-hook timeout configured in settings files, up to 60 seconds. Timeouts set on plugin-provided hooks do not raise the budget. To override the budget explicitly, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable in milliseconds.
+SessionEnd hooks have no decision control. They can’t block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If a hook needs more time, set a per-hook `timeout` in the hook configuration. The overall budget is automatically raised to the highest per-hook timeout configured in settings files, up to 60 seconds. Timeouts set on plugin-provided hooks don’t raise the budget. To override the budget explicitly, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable in milliseconds.
CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude
@@ -2626,7 +2650,7 @@
Elicitation input
-In addition to the common input fields, Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields. For form-mode elicitation (the most common case):
+In addition to the common input fields, Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields. For form-mode elicitation, the most common case:
{
"session_id": "abc123",
@@ -2645,7 +2669,7 @@
}
}
-For URL-mode elicitation (browser-based authentication):
+For URL-mode elicitation, used for browser-based authentication:
{
"session_id": "abc123",
@@ -2775,7 +2799,7 @@
* `WorktreeCreate`
* `WorktreeRemove`
-`SessionStart` and `Setup` support `command` and `mcp_tool` hooks. They do not support `http`, `prompt`, or `agent` hooks.
+`SessionStart` and `Setup` support `command` and `mcp_tool` hooks. They don’t support `http`, `prompt`, or `agent` hooks.
###
@@ -2847,7 +2871,7 @@
* `PostToolUseFailure`, `TaskCreated`, and `TaskCompleted`: the reason is returned to Claude as a tool error, similar to `PreToolUse`
* `TeammateIdle`: by default the teammate stops and the reason appears as a warning line. Set `continueOnBlock: true` to feed the reason back to the teammate and keep it working instead
* `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a command hook returning `hookSpecificOutput.decision.behavior: "deny"`
- * `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks cannot set. They run on this event, but their output is discarded. Use a command hook to return `retry`
+ * `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks can’t set. They run on this event, but their output is discarded. Use a command hook to return `retry`
If you need finer control on any event, use a command hook with the per-event fields described in Decision control.
@@ -2855,9 +2879,9 @@
-Example: Multi-criteria Stop hook
-
-This `Stop` hook uses a detailed prompt to check three conditions before allowing Claude to stop. If `"ok"` is `false`, Claude continues working with the provided reason as its next instruction. `SubagentStop` hooks use the same format to evaluate whether a [subagent](</docs/en/sub-agents>) should stop:
+Check multiple conditions before stopping
+
+This `Stop` hook uses a detailed prompt to check three conditions before allowing Claude to stop. `SubagentStop` hooks use the same format to evaluate whether a [subagent](</docs/en/sub-agents>) should stop. If `"ok"` is `false`, Claude continues working with the provided reason as its next instruction:
{
"hooks": {
@@ -2939,7 +2963,7 @@
Run hooks in the background
-By default, hooks block Claude’s execution until they complete. For long-running tasks like deployments, test suites, or external API calls, set `"async": true` to run the hook in the background while Claude continues working. Async hooks cannot block or control Claude’s behavior: response fields like `decision`, `permissionDecision`, and `continue` have no effect, because the action they would have controlled has already completed.
+By default, hooks block Claude’s execution until they complete. For long-running tasks like deployments, test suites, or external API calls, set `"async": true` to run the hook in the background while Claude continues working. Async hooks can’t block or control Claude’s behavior: response fields like `decision`, `permissionDecision`, and `continue` have no effect, because the action they would have controlled has already completed.
###
@@ -2981,7 +3005,7 @@
-Example: run tests after file changes
+Run tests after file changes
This hook starts a test suite in the background whenever Claude writes a file, then reports the results back to Claude when the tests finish. Save this script to `.claude/hooks/run-tests-async.sh` in your project and make it executable with `chmod +x`:
@@ -3037,8 +3061,8 @@
Async hooks have several constraints compared to synchronous hooks:
- * Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.
- * Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
+ * Only `type: "command"` hooks support `async`. Prompt-based hooks can’t run asynchronously.
+ * Async hooks can’t block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.
* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction. Exception: an `asyncRewake` hook that exits with code 2 wakes Claude immediately even when the session is idle.
* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.
@@ -3078,7 +3102,7 @@
Windows PowerShell tool
-On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe` (PowerShell 7+) with a fallback to `powershell.exe` (5.1).
+On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe`, the PowerShell 7 and later executable, and falls back to `powershell.exe` for Windows PowerShell 5.1.
{
"hooks": {
@@ -3097,7 +3121,7 @@
}
}
-To reference the project root from a PowerShell shell-form command, read it as an environment variable with `$env:CLAUDE_PROJECT_DIR`. PowerShell treats the bare `${CLAUDE_PROJECT_DIR}` form as a local variable, not an environment lookup, and Claude Code substitutes that placeholder in shell form only for plugin hooks. For a hook defined in `settings.json`, either use the `$env:` form or switch to exec form, where `${CLAUDE_PROJECT_DIR}` is substituted in each `args` element regardless of where the hook is defined. The example below shows a `settings.json` hook that runs a project script with the `$env:` form:
+To reference the project root from a PowerShell shell-form command, write `${CLAUDE_PROJECT_DIR}` or `$env:CLAUDE_PROJECT_DIR`. As of v2.1.198, Claude Code rewrites the `${CLAUDE_PROJECT_DIR}`, `${CLAUDE_PLUGIN_ROOT}`, and `${CLAUDE_PLUGIN_DATA}` placeholders in a PowerShell shell-form command to PowerShell’s `${env:NAME}` form, whether the hook is defined in `settings.json`, a plugin, or a skill. PowerShell then resolves the value from the exported environment after parsing, so the placeholder works inside double-quoted strings but not inside single-quoted strings, where PowerShell never expands variables. Before v2.1.198, this rewrite applied only to plugin hooks. On earlier versions, a `settings.json` hook needs the `$env:` form or exec form, where `${CLAUDE_PROJECT_DIR}` is substituted in each `args` element regardless of where the hook is defined. Don’t write the bare `$CLAUDE_PROJECT_DIR` spelling in a PowerShell hook. PowerShell parses it as an undefined local variable and resolves it to `$null`, which leaves the script path without its project-root prefix. Claude Code doesn’t rewrite that form; it logs a warning in the debug log instead. The example below shows a `settings.json` hook that runs a project script with the `$env:` form, which works on every version:
{
"type": "command",
@@ -3111,7 +3135,7 @@
Debug hooks
-Hook execution details, including which hooks matched, their exit codes, and full stdout and stderr, are written to the debug log file. Start Claude Code with `claude --debug-file <path>` to write the log to a known location, or run `claude --debug` and read the log at `~/.claude/debug/<session-id>.txt`. The `--debug` flag does not print to the terminal.
+Hook execution details, including which hooks matched, their exit codes, and full stdout and stderr, are written to the debug log file. Start Claude Code with `claude --debug-file <path>` to write the log to a known location, or run `claude --debug` and read the log at `~/.claude/debug/<session-id>.txt`. The `--debug` flag doesn’t print to the terminal.
[DEBUG] Executing hooks for PostToolUse:Write
[DEBUG] Found 1 hook commands to execute
Show diff (306 lines)
--- a/hooks-guide.md
+++ b/hooks-guide.md
@@ -73,17 +73,7 @@
What you can automate
-Hooks let you run code at key points in Claude Code’s lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](</docs/en/hooks#hook-lifecycle>). Each example includes a ready-to-use configuration block that you add to a settings file. The most common patterns:
-
- * Get notified when Claude needs input
- * Auto-format code after edits
- * Block edits to protected files
- * Re-inject context after compaction
- * Audit configuration changes
- * Reload environment when directory or files change
- * Auto-approve specific permission prompts
-
-For a production example of hooks that run a separate model review and feed findings back into the session, see [how the `security-guidance` plugin integrates with Claude Code](</docs/en/security-guidance#how-the-plugin-integrates-with-claude-code>).
+Hooks let you run code at key points in Claude Code’s lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](</docs/en/hooks#hook-lifecycle>). Each example includes a ready-to-use configuration block that you add to a settings file. For a production example of hooks that run a separate model review and feed findings back into the session, see [how the `security-guidance` plugin integrates with Claude Code](</docs/en/security-guidance#how-the-plugin-integrates-with-claude-code>).
###
@@ -165,8 +155,10 @@
`elicitation_dialog`| An MCP server opens an elicitation form
`elicitation_complete`| An MCP elicitation form is submitted or dismissed
`elicitation_response`| An MCP elicitation response is sent back to the server
-
-Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
+`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open
+`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open
+
+The `agent_needs_input` and `agent_completed` matchers require Claude Code v2.1.198 or later. Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](</docs/en/hooks#notification>).
###
@@ -174,7 +166,7 @@
Auto-format code after edits
-Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions. The command extracts the edited file path with [`jq`](<https://jqlang.github.io/jq/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
+Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](<https://jqlang.github.io/jq/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:
{
"hooks": {
@@ -192,7 +184,9 @@
}
}
-The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` (macOS), `apt-get install jq` (Debian/Ubuntu), or see [`jq` downloads](<https://jqlang.github.io/jq/download/>).
+On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.
+
+The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.github.io/jq/download/>).
###
@@ -227,7 +221,7 @@
2
-Make the script executable (macOS/Linux)
+Make the script executable on macOS and Linux
Hook scripts must be executable for Claude Code to run them:
@@ -313,7 +307,7 @@
Reload environment when directory or files change
-Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool does not pick up those changes on its own. Pairing a `SessionStart` hook with a `CwdChanged` hook fixes this. `SessionStart` loads the variables for the directory you launch in, and `CwdChanged` reloads them each time Claude changes directory. Both write to `CLAUDE_ENV_FILE`, which Claude Code runs as a script preamble before each Bash command. Add this to `~/.claude/settings.json`:
+Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool doesn’t pick up those changes on its own. Pairing a `SessionStart` hook with a `CwdChanged` hook fixes this. `SessionStart` loads the variables for the directory you launch in, and `CwdChanged` reloads them each time Claude changes directory. Both write to `CLAUDE_ENV_FILE`, which Claude Code runs as a script preamble before each Bash command. Add this to `~/.claude/settings.json`:
{
"hooks": {
@@ -340,7 +334,7 @@
}
}
-Run `direnv allow` once in each directory that has an `.envrc` so direnv is permitted to load it. If you use devbox or nix instead of direnv, the same pattern works with `devbox shellenv` or `devbox global shellenv` in place of `direnv export bash`. To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch, separated by `|`. To build the watch list, this value is split into literal filenames rather than evaluated as a regex. See [FileChanged](</docs/en/hooks#filechanged>) for how the same value also filters which hook groups run when a file changes. This example watches `.envrc` and `.env` in the working directory:
+Run `direnv allow` once in each directory that has an `.envrc` so direnv is permitted to load it. If you use devbox or nix instead of direnv, the same pattern works with `devbox shellenv` or `devbox global shellenv` in place of `direnv export bash`. To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch, separated by `|`. When building the watch list, Claude Code splits this value into literal filenames rather than evaluating it as a regex. See [FileChanged](</docs/en/hooks#filechanged>) for how the same value also filters which hook groups run when a file changes. This example watches `.envrc` and `.env` in the working directory:
{
"hooks": {
@@ -384,7 +378,7 @@
}
}
-When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it cannot clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.
+When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows “Allowed by PermissionRequest hook” where the dialog would have appeared. The hook path always keeps the current conversation: it can’t clear context and start a fresh implementation session the way the dialog can. To set a specific permission mode instead, your hook’s output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.
`bypassPermissions` only applies if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and not disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>). It is never persisted as `defaultMode`.
@@ -458,7 +452,7 @@
Combine results from multiple hooks
-When multiple hooks match the same event, every hook’s command runs to completion before Claude Code merges the results. One hook returning `deny` does not stop sibling hooks from executing. Don’t rely on one hook’s `deny` to suppress side effects in another hook. After all matching hooks finish, Claude Code combines their outputs. For `PreToolUse` permission decisions, the most restrictive answer wins, in the order `deny`, `defer`, `ask`, `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. The example below registers two `PreToolUse` hooks on `Bash`. The first appends every command to a log file and exits 0. The second runs a script that exits 2 to deny when the command contains `rm -rf`:
+When multiple hooks match the same event, every hook’s command runs to completion before Claude Code merges the results. One hook returning `deny` doesn’t stop sibling hooks from executing. Don’t rely on one hook’s `deny` to suppress side effects in another hook. After all matching hooks finish, Claude Code combines their outputs. For `PreToolUse` permission decisions, the most restrictive answer applies, in the order `deny`, `defer`, `ask`, `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. The example below registers two `PreToolUse` hooks on `Bash`. The first appends every command to a log file and exits 0. The second runs a script that exits 2 to deny when the command contains `rm -rf`:
{
"hooks": {
@@ -480,7 +474,7 @@
}
}
-When Claude tries to run `rm -rf /tmp/build`, both hooks execute in parallel. The logging hook writes the command to `~/.claude/bash.log` and exits 0, which reports no decision. The guardrail hook exits 2, which denies the tool call. The deny wins, so Claude Code blocks the command and shows Claude the guardrail’s stderr. The log entry is still written because the logging hook already ran.
+When Claude tries to run `rm -rf /tmp/build`, both hooks execute in parallel. The logging hook writes the command to `~/.claude/bash.log` and exits 0, which reports no decision. The guardrail hook exits 2, which denies the tool call. The deny takes precedence, so Claude Code blocks the command and shows Claude the guardrail’s stderr. The log entry is still written because the logging hook already ran.
###
@@ -508,7 +502,7 @@
}
}
-Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get the `source` (startup, resume, clear, compact), and so on. See [Common input fields](</docs/en/hooks#common-input-fields>) in the reference for shared fields, and each event’s section for event-specific schemas.
+Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get a `source` of `startup`, `resume`, `clear`, or `compact`, and so on. See [Common input fields](</docs/en/hooks#common-input-fields>) in the reference for shared fields, and each event’s section for event-specific schemas.
####
@@ -516,7 +510,7 @@
Hook output
-Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. For example, a `PreToolUse` hook that wants to block a command:
+Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. The following `PreToolUse` hook blocks a command:
#!/bin/bash
INPUT=$(cat)
@@ -532,7 +526,7 @@
The exit code determines what happens next:
* **Exit 0** : the hook reports no objection and the action proceeds normally. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context.
- * **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events cannot be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
+ * **Exit 2** : the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events can’t be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list.
* **Any other exit code** : the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](</docs/en/hooks#debug-hooks>).
####
@@ -561,7 +555,7 @@
* `"deny"`: cancel the tool call and send the reason to Claude
* `"ask"`: show the permission prompt to the user as normal
-A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Returning `"allow"` skips the interactive prompt but does not override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted. This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude’s context. Prompt-based hooks (`type: "prompt"`) handle output differently: see Prompt-based hooks.
+A fourth value, `"defer"`, is available in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) in the reference. Returning `"allow"` skips the interactive prompt but doesn’t override [permission rules](</docs/en/permissions#manage-permissions>). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted. This means deny rules from any settings scope, including [managed settings](</docs/en/settings#settings-files>), always take precedence over hook approvals. Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](</docs/en/hooks#decision-control>) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude’s context. Hooks with `type: "prompt"` handle output differently: see Prompt-based hooks.
###
@@ -569,7 +563,7 @@
Filter hooks with matchers
-Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits (not after every tool call), add a matcher to your `PostToolUse` hook:
+Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits, not after every tool call, add a matcher to your `PostToolUse` hook:
{
"hooks": {
@@ -596,7 +590,7 @@
`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`
`Setup`| which CLI flag triggered setup| `init`, `maintenance`
`SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other`
-`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`
+`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed`
`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names
`PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto`
`SubagentStop`| agent type| same values as `SubagentStart`
@@ -609,7 +603,7 @@
`UserPromptExpansion`| command name| your skill or command names
`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`, `MessageDisplay`| no matcher support| always fires on every occurrence
-A few more examples showing matchers on different event types:
+The tabs below show a few more matchers on different event types.
* Log every Bash command
@@ -617,7 +611,7 @@
* Clean up on session end
-Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts just the command string, which `>>` appends to the log file:
+Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts only the command string, which `>>` appends to the log file:
{
"hooks": {
@@ -653,7 +647,7 @@
}
}
-The `SessionEnd` event supports matchers on the reason the session ended. This hook only fires on `clear` (when you run `/clear`), not on normal exits:
+The `SessionEnd` event supports matchers on the reason the session ended. This hook only fires on the `clear` reason, set when you run `/clear`, not on normal exits:
{
"hooks": {
@@ -681,7 +675,7 @@
The `if` field requires Claude Code v2.1.85 or later. Earlier versions ignore it and run the hook on every matched call.
-The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:
+The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, this configuration runs a hook only when Claude uses `git` commands rather than all Bash commands:
{
"hooks": {
@@ -710,7 +704,7 @@
`Bash(git *)`| `echo $(date)`| no| no subcommand matches `git *`
`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR`
-The filter also fails open, running your hook regardless of pattern, when the Bash command cannot be parsed. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
+The filter also fails open, running your hook regardless of pattern, when the Bash command can’t be parsed. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.
###
@@ -737,7 +731,7 @@
Prompt-based hooks
-For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model (Haiku by default) to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return a yes/no decision as JSON:
+For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model, Haiku by default, to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return a yes/no decision as JSON:
* `"ok": true`: the action proceeds
* `"ok": false`: what happens depends on the event:
@@ -772,7 +766,7 @@
Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](</docs/en/hooks#command-hook-fields>).
-When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. This example verifies that tests pass before allowing Claude to stop:
+When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. This example verifies that tests pass before allowing Claude to stop:
{
"hooks": {
@@ -819,7 +813,7 @@
}
}
-The endpoint should return a JSON response body using the same [output format](</docs/en/hooks#json-output>) as command hooks. To block a tool call, return a 2xx response with the appropriate `hookSpecificOutput` fields. HTTP status codes alone cannot block actions. Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference.
+The endpoint should return a JSON response body using the same [output format](</docs/en/hooks#json-output>) as command hooks. To block a tool call, return a 2xx response with the appropriate `hookSpecificOutput` fields. HTTP status codes alone can’t block actions. Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference.
##
@@ -833,15 +827,17 @@
Limitations
- * Command hooks communicate through stdout, stderr, and exit codes only. They cannot trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.
+Keep these constraints in mind when designing hooks:
+
+ * Command hooks communicate through stdout, stderr, and exit codes only. They can’t trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.
* Hook timeouts vary by type. Override per hook with the `timeout` field in seconds.
* `command`, `http`, `mcp_tool`: 10 minutes. `UserPromptSubmit` lowers these to 30 seconds, and `MessageDisplay` lowers them to 10 seconds.
* `prompt`: 30 seconds.
* `agent`: 60 seconds.
- * `PostToolUse` hooks cannot undo actions since the tool has already executed.
- * `PermissionRequest` hooks do not fire in [non-interactive mode](</docs/en/headless>) (`-p`). Use `PreToolUse` hooks for automated permission decisions.
- * `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
- * When multiple PreToolUse hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s arguments, the last one to finish wins. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool’s input.
+ * `PostToolUse` hooks can’t undo actions since the tool has already executed.
+ * `PermissionRequest` hooks don’t fire in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Use `PreToolUse` hooks for automated permission decisions.
+ * `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don’t fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead.
+ * When multiple `PreToolUse` hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s arguments, the last one to finish takes effect. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool’s input.
###
@@ -849,7 +845,7 @@
Hooks and permission modes
-PreToolUse hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users cannot bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` does not bypass deny rules from settings. Hooks can tighten restrictions but not loosen them past what permission rules allow.
+`PreToolUse` hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can’t bypass by changing their permission mode. The reverse is not true: a hook returning `"allow"` doesn’t bypass deny rules from settings. Hooks can tighten restrictions but not loosen them past what permission rules allow.
###
@@ -860,9 +856,9 @@
The hook is configured but never executes.
* Run `/hooks` and confirm the hook appears under the correct event
- * Check that the matcher pattern matches the tool name exactly (matchers are case-sensitive)
- * Verify you’re triggering the right event type (e.g., `PreToolUse` fires before tool execution, `PostToolUse` fires after)
- * If using `PermissionRequest` hooks in non-interactive mode (`-p`), switch to `PreToolUse` instead
+ * Check that the matcher pattern matches the tool name exactly. Matchers are case-sensitive
+ * Verify you’re triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after
+ * If using `PermissionRequest` hooks in non-interactive mode with the `-p` flag, switch to `PreToolUse` instead
###
@@ -890,7 +886,7 @@
You edited a settings file but the hooks don’t appear in the menu.
* File edits are normally picked up automatically. If they haven’t appeared after a few seconds, the file watcher may have missed the change: restart your session to force a reload.
- * Verify your JSON is valid (trailing commas and comments are not allowed)
+ * Verify your JSON is valid: trailing commas and comments aren’t allowed
* Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks
###
@@ -899,7 +895,7 @@
Stop hook hits the block cap
-Claude keeps working instead of stopping, then ends the turn with a warning that the Stop hook blocked too many consecutive times. Claude Code overrides a Stop hook after it blocks 8 times in a row without progress. Your hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
+Claude keeps working instead of stopping, then ends the turn with a warning that the Stop hook blocked too many consecutive times. Claude Code overrides a Stop hook after it blocks eight times in a row without progress. Your hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`:
#!/bin/bash
INPUT=$(cat)
@@ -916,7 +912,7 @@
JSON validation failed
-Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a shell-form command hook (one without `args`), it spawns `sh -c` on macOS and Linux or Git Bash on Windows by default. This shell is non-interactive, but Git Bash and some configurations (such as `BASH_ENV` pointing at `~/.bashrc`) still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
+Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux or Git Bash on Windows by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON:
Shell ready on arm64
{"decision": "block", "reason": "Not allowed"}
--- a/how-claude-code-works.md
+++ b/how-claude-code-works.md
@@ -188,7 +188,6 @@
Claude Code can teach you how to use it. Ask questions like “how do I set up hooks?” or “what’s the best way to structure my CLAUDE.md?” and Claude will explain. Built-in commands also guide you through setup:
* `/init` walks you through creating a CLAUDE.md for your project
- * `/agents` helps you configure custom subagents
* `/doctor` diagnoses common issues with your installation
###
--- a/interactive-mode.md
+++ b/interactive-mode.md
@@ -29,7 +29,7 @@
`Ctrl+R`| Reverse search command history| Search through previous commands interactively
`Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows and WSL)| Paste image from clipboard| Inserts an `[Image #N]` chip at the cursor so you can reference it positionally in your prompt. On WSL, both `Ctrl+V` and `Alt+V` are bound; use `Alt+V` if your terminal intercepts `Ctrl+V`
`Ctrl+B`| Background running tasks| Backgrounds Bash commands and agents. Tmux users press twice
-`Ctrl+T`| Toggle task list| Show or hide the task list in the terminal status area
+`Ctrl+T`| Toggle Claude’s task checklist| Show or hide Claude’s to-do checklist in the status area. This is not the background-task view; use [`/tasks`](</docs/en/commands>) to see running shells and subagents
`Left/Right arrows`| Cycle through dialog tabs| Navigate between tabs in permission dialogs and menus
`Up/Down arrows` or `Ctrl+P`/`Ctrl+N`| Move cursor or navigate command history| When the input spans more than one visual row, whether wrapped or multiline, first moves the cursor within the prompt. Once the cursor is on the first or last visual row, pressing again navigates command history. As of v2.1.169, wrapped single-line input behaves the same as multiline
`Esc`| Interrupt Claude| Stop the current response or tool call mid-turn so you can redirect. Claude keeps the work done so far
@@ -397,9 +397,9 @@
Task list
-When working on complex, multi-step work, Claude creates a task list to track progress. Tasks appear in the status area of your terminal with indicators showing what’s pending, in progress, or complete.
-
- * Press `Ctrl+T` to toggle the task list view. The display shows up to 5 tasks at a time
+The task list is Claude’s to-do checklist: items Claude created to plan multi-step work, with indicators showing what’s pending, in progress, or complete. It’s separate from the background-task view. To see running shells and subagents, use [`/tasks`](</docs/en/commands>) instead.
+
+ * Press `Ctrl+T` to toggle the task list view. The display shows up to five tasks at a time. When Claude hasn’t created any checklist items yet, the toggle has no visible effect because there’s nothing to display
* To see all tasks or clear them, ask Claude directly: “show me all tasks” or “clear all tasks”
* Tasks persist across context compactions, helping Claude stay organized on larger projects
* To share a task list across sessions, set `CLAUDE_CODE_TASK_LIST_ID` to use a named directory in `~/.claude/tasks/`: `CLAUDE_CODE_TASK_LIST_ID=my-project claude`
--- a/keybindings.md
+++ b/keybindings.md
@@ -86,7 +86,7 @@
`app:interrupt`| Ctrl+C| Cancel current operation
`app:exit`| Ctrl+D| Exit Claude Code
`app:redraw`| (unbound)| Force terminal redraw
-`app:toggleTodos`| Ctrl+T| Toggle task list visibility
+`app:toggleTodos`| Ctrl+T| Toggle visibility of Claude’s to-do checklist. This is not the [`/tasks`](</docs/en/commands>) background-task view
`app:toggleTranscript`| Ctrl+O| Toggle verbose transcript
###
--- a/mcp.md
+++ b/mcp.md
@@ -888,6 +888,37 @@
+Tool input schemas with a root-level combinator
+
+Some MCP servers declare a tool’s input schema as a JSON Schema union, with `anyOf`, `oneOf`, or `allOf` at the top level of the schema. The Claude API doesn’t accept those keywords at the schema root. It does accept combinators nested inside `properties`, which Claude Code sends unchanged. As of Claude Code v2.1.195, tools with a root-level combinator stay available. Before sending the tool to the API, Claude Code flattens the schema into a single object and prepends a sentence to the tool’s description that tells Claude which parameter groups belong together:
+
+ * `allOf`: properties from every branch are merged, and each branch’s `required` list still applies
+ * `anyOf` and `oneOf`: properties from every branch are merged, and each branch’s `required` list is described in the tool description instead of enforced by the schema
+
+Your server receives whichever arguments Claude chose, so keep validating the combination server-side. When Claude Code can’t produce a schema the API accepts, or on a deployment that doesn’t receive the remote configuration that enables the rewrite, such as an offline machine, it skips that one tool, records the reason in the server’s log, and leaves the server’s other tools available. Versions earlier than v2.1.195 skip every tool whose input schema has a root-level `anyOf`, `oneOf`, or `allOf`.
+
+##
+
+
+
+Require approval for a specific tool
+
+If you’re building an MCP server, you can mark a tool as requiring explicit approval on every call by setting `_meta["anthropic/requiresUserInteraction"]` to `true` in the tool’s `tools/list` response entry. The value must be the JSON boolean `true`; any other value is ignored. Claude Code shows that tool’s permission prompt on every call, even in `acceptEdits`, `auto`, and `bypassPermissions` [permission modes](</docs/en/permissions#permission-modes>), and doesn’t offer a “don’t ask again” option for it. [Allow rules](</docs/en/permissions#permission-rule-syntax>) that match the tool don’t skip the prompt either. In `dontAsk` mode, which never prompts, Claude Code denies the call instead. The prompt has to reach a person. In non-interactive mode with [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>), an `allow` result from the prompt tool for a flagged tool is converted to a deny with the message `MCP tool requires user interaction; not supported via --permission-prompt-tool`. The Agent SDK’s [`canUseTool` callback](</docs/en/agent-sdk/permissions>) does receive these calls and can approve them, because the SDK host is expected to show them to a user. Use this for tools whose permission prompt is itself the point, such as a consent or access-grant step where auto-approval would mean no human ever agreed. Other tools from the same server keep their normal permission behavior. The following `tools/list` entry marks one tool as always requiring approval.
+
+ {
+ "name": "grant_access",
+ "description": "Requests access to a protected resource",
+ "_meta": {
+ "anthropic/requiresUserInteraction": true
+ }
+ }
+
+The `anthropic/requiresUserInteraction` annotation requires Claude Code v2.1.199 or later. Earlier versions ignore it and apply the standard permission flow. When a session is connected to [Remote Control](</docs/en/remote-control>) or an SDK host, Claude Code marks the permission request as requiring user interaction, so the client shows the tool’s permission prompt for you to answer instead of a one-tap approve action.
+
+##
+
+
+
Respond to MCP elicitation requests
MCP servers can request structured input from you mid-task using elicitation. When a server needs information it can’t get on its own, Claude Code displays an interactive dialog and passes your response back to the server. No configuration is required on your side: elicitation dialogs appear automatically when a server requests them. Servers can request input in two ways:
--- a/memory.md
+++ b/memory.md
@@ -205,7 +205,7 @@
- Use the standard error response format
- Include OpenAPI documentation comments
-Rules without a `paths` field are loaded unconditionally and apply to all files. Path-scoped rules trigger when Claude reads files matching the pattern, not on every tool use. Use glob patterns in the `paths` field to match files by extension, directory, or any combination:
+Rules without a `paths` field are loaded unconditionally and apply to all files. Path-scoped rules trigger when Claude reads files matching the pattern, not on every tool use. As of v2.1.198, matching also works when Claude reaches a file through a symlinked path to the project directory, for example in a symlinked checkout. Use glob patterns in the `paths` field to match files by extension, directory, or any combination:
Pattern| Matches
---|---
Show diff (106 lines)
--- a/model-config.md
+++ b/model-config.md
@@ -25,7 +25,7 @@
Model alias| Behavior
---|---
-**`default`**| Special value that clears any model override and reverts to the recommended model for your account type. Not itself a model alias
+**`default`**| Special value that clears any model override and reverts to the recommended model for your account type, or to the organization default model when an admin has set one. Not itself a model alias
**`best`**| Uses Fable 5 where your organization has access to it, otherwise the latest Opus model
**`fable`**| Uses Claude Fable 5 for your hardest and longest-running tasks
**`sonnet`**| Uses the latest Sonnet model for daily coding tasks
@@ -72,7 +72,7 @@
* `Enter`: switch model and save as your default
* `s`: switch model for this session only
-Typing `/model <name>` directly behaves like `Enter`. Project and managed settings still take precedence and reapply on the next launch. In v2.1.144 through v2.1.152, `/model` applied to the current session only and `d` in the picker saved a default. The `--model` flag and `ANTHROPIC_MODEL` environment variable apply only to the session you launch with them. To run different models in different terminals at the same time, launch each one with its own `--model` flag rather than switching with `/model`. Resumed sessions started with `claude --resume`, `--continue`, or the `/resume` picker keep the model they were using when the transcript was saved, regardless of the current `model` setting. If the restored model has been retired or is excluded by `availableModels`, the session falls through to the normal precedence order. This prevents another session’s `/model` choice from changing the model on resume. A model you pick for the new launch with `--model` or `ANTHROPIC_MODEL` still takes precedence over the restored model. As of v2.1.195, so does an `ANTHROPIC_DEFAULT_OPUS_MODEL` family variable. When the active model at startup comes from project or managed settings rather than your own selection, the startup header shows which settings file set it. Run `/model` to override; the project or managed setting reapplies on the next launch. When the requested model has a scheduled retirement date or is automatically remapped to a newer version, Claude Code shows a warning that names the requested model. Interactive sessions show it as a startup notice. From v2.1.182, the same warning is written to stderr in [non-interactive mode](</docs/en/headless>) when using the default text output format. The check also covers a `model` set in [subagent frontmatter](</docs/en/sub-agents>). The stderr warning is suppressed for `--output-format json` and `stream-json`; read the actual model from the `modelUsage` field of the [result message](</docs/en/headless#get-structured-output>) instead. Example usage:
+Typing `/model <name>` directly behaves like `Enter`. Project and managed settings still take precedence and reapply on the next launch. An organization default model that your admin has configured to override user selection also reapplies on the next launch. In v2.1.144 through v2.1.152, `/model` applied to the current session only and `d` in the picker saved a default. The `--model` flag and `ANTHROPIC_MODEL` environment variable apply only to the session you launch with them. To run different models in different terminals at the same time, launch each one with its own `--model` flag rather than switching with `/model`. Resumed sessions started with `claude --resume`, `--continue`, or the `/resume` picker keep the model they were using when the transcript was saved, regardless of the current `model` setting. If the restored model has been retired or is excluded by `availableModels`, the session falls through to the normal precedence order. This prevents another session’s `/model` choice from changing the model on resume. A model you pick for the new launch with `--model` or `ANTHROPIC_MODEL` still takes precedence over the restored model. As of v2.1.195, so does an `ANTHROPIC_DEFAULT_OPUS_MODEL` family variable. When the active model at startup comes from project or managed settings rather than your own selection, the startup header shows which settings file set it. Run `/model` to override; the project or managed setting reapplies on the next launch. When the requested model has a scheduled retirement date or is automatically remapped to a newer version, Claude Code shows a warning that names the requested model. Interactive sessions show it as a startup notice. From v2.1.182, the same warning is written to stderr in [non-interactive mode](</docs/en/headless>) when using the default text output format. The check also covers a `model` set in [subagent frontmatter](</docs/en/sub-agents>). The stderr warning is suppressed for `--output-format json` and `stream-json`; read the actual model from the `modelUsage` field of the [result message](</docs/en/headless#get-structured-output>) instead. Example usage:
# Start with Opus
claude --model opus
@@ -100,12 +100,12 @@
* **Main session model** : `/model`, the `--model` flag, the `ANTHROPIC_MODEL` environment variable, the `model` setting, and the model restored when resuming a session
* **Alias resolution** : the `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, `ANTHROPIC_DEFAULT_HAIKU_MODEL`, and `ANTHROPIC_DEFAULT_FABLE_MODEL` environment variables cannot redirect an allowed alias to a model outside the list
* **Fast mode** : `/fast` refuses to toggle when it would implicitly switch to an Opus model outside the list, with the message “is not in your organization’s allowed models”
- * **Subagent models** : the `model` field in [subagent](</docs/en/sub-agents#choose-a-model>) frontmatter, the Agent tool’s `model` parameter, the model picker in `/agents`, and `CLAUDE_CODE_SUBAGENT_MODEL`
+ * **Subagent models** : the `model` field in [subagent](</docs/en/sub-agents#choose-a-model>) frontmatter, the Agent tool’s `model` parameter, `CLAUDE_CODE_SUBAGENT_MODEL`, and, on v2.1.197 and earlier, the model picker in the `/agents` wizard
* **Skill and command models** : the `model` frontmatter in [skills and commands](</docs/en/skills>)
* **Advisor model** : the configured [`advisorModel`](</docs/en/advisor>) setting and the `--advisor` flag
* **Background agent model** : the model selected in the [dispatch picker](</docs/en/agent-view>)
-Switching to a blocked model with `/model` is rejected with an error, while a blocked `--model` flag, `ANTHROPIC_MODEL`, or `model` setting value is replaced at startup with a warning naming both the requested and substituted models, and the session starts on the default model. A blocked subagent, skill, or command override falls back to the inherited or default model rather than failing the request; a blocked `advisorModel` setting disables the advisor for the session, while a blocked `--advisor` flag value exits with an error at launch. Excluded models are hidden from the `/model` picker. Automatic model changes are checked the same way: elements of a fallback model chain outside the allowlist are dropped, a plan-mode upgrade such as `opusplan` to an excluded model is skipped so planning continues on the session’s model, and an automatic model fallback whose target is excluded does not run, so the flagged request ends with a refusal instead. Enabling [fast mode](</docs/en/fast-mode>) is refused when the model the session would run on afterward is outside the allowlist.
+Switching to a blocked model with `/model` is rejected with an error, while a blocked `--model` flag, `ANTHROPIC_MODEL`, or `model` setting value is replaced at startup with a warning naming both the requested and substituted models, and the session starts on the default model. A blocked subagent, skill, or command override falls back to the inherited or default model rather than failing the request; a blocked `advisorModel` setting disables the advisor for the session, while a blocked `--advisor` flag value exits with an error at launch. Excluded models are hidden from the `/model` picker. As of v2.1.199, a full model ID in the list that has no built-in picker row, such as an older version that the list pins, appears in the `/model` picker as its own labeled row. On earlier versions such an ID is selectable only by typing `/model <id>`. Automatic model changes are checked the same way: elements of a fallback model chain outside the allowlist are dropped, a plan-mode upgrade such as `opusplan` to an excluded model is skipped so planning continues on the session’s model, and an automatic model fallback whose target is excluded does not run, so the flagged request ends with a refusal instead. Enabling [fast mode](</docs/en/fast-mode>) is refused when the model the session would run on afterward is outside the allowlist.
{
"availableModels": ["sonnet", "haiku"]
@@ -152,7 +152,7 @@
"enforceAvailableModels": true
}
-When the default model for the user’s account type is not in the allowlist, the Default option instead resolves to the first `availableModels` entry that names an allowed, available model, and the `/model` picker’s Default row shows that model. This applies everywhere the default is reached: session startup, selecting Default in `/model`, the `"default"` keyword in fallback model chains, and the fallback used when an excluded selection is dropped. `enforceAvailableModels` has no effect when `availableModels` is unset or empty: with `availableModels: []`, the Default model for the account type remains usable, so the setting cannot lock users out of every model. When `availableModels` is non-empty but no entry resolves to an allowed and available model, enforcement is skipped and Default resolves to the account-type default, with a warning visible only under `--debug`. Keep at least one guaranteed-available entry in the list to avoid this. Deploy both keys in the [highest-precedence managed source](</docs/en/settings#settings-precedence>): admin-deployed managed sources do not merge, so a pair placed in a managed settings file is ignored when the admin console delivers any settings.
+The Default option resolves to the account-type default, or to the organization default model when an admin has set one. When that model is not in the allowlist, the Default option instead resolves to the first `availableModels` entry that names an allowed, available model, and the `/model` picker’s Default row shows that model. This applies everywhere the default is reached: session startup, selecting Default in `/model`, the `"default"` keyword in fallback model chains, and the fallback used when an excluded selection is dropped. `enforceAvailableModels` has no effect when `availableModels` is unset or empty: with `availableModels: []`, the Default model for the account type remains usable, so the setting cannot lock users out of every model. When `availableModels` is non-empty but no entry resolves to an allowed and available model, enforcement is skipped and Default resolves to the account-type default, with a warning visible only under `--debug`. Keep at least one guaranteed-available entry in the list to avoid this. Deploy both keys in the [highest-precedence managed source](</docs/en/settings#settings-precedence>): admin-deployed managed sources do not merge, so a pair placed in a managed settings file is ignored when the admin console delivers any settings.
###
@@ -202,7 +202,42 @@
Organization model restrictions
-Organization admins on Claude Enterprise plans restrict which models members can run by disabling individual models in the claude.ai admin console. This restriction is delivered with the account’s entitlements when Claude Code authenticates, separate from any `availableModels` list in settings, and the server enforces the same restriction independently when a session is created. Requires Claude Code v2.1.187 or later. The restriction applies when a member signs in or uses their own API key. Organization-scoped credentials, such as organization service keys, are not tied to a user, so the restriction does not apply to them. The Claude Console has no model restriction control. Organizations without a Claude Enterprise plan, including those whose members authenticate through the Anthropic API, restrict models with `availableModels` in [managed settings](</docs/en/settings#settings-files>) instead, adding `enforceAvailableModels` to cover the Default option. These settings are enforced by Claude Code itself, not by the server. A restricted model is hidden from the `/model` picker. Selecting it by name with `--model`, the `ANTHROPIC_MODEL` environment variable, or the `model` setting shows the notice `Model "<name>" is restricted by your organization's settings. Using <model> instead.` and the session starts on an allowed model. Typing `/model <name>` for a restricted model is rejected with `Model '<name>' is restricted by your organization's settings. Run /model to choose a different model.` and the session keeps its current model. Both restrictions apply together: a model is selectable only when it is permitted by `availableModels` and not restricted by the organization. Organization restrictions are delivered to sessions on the Anthropic API and [LLM gateway](</docs/en/llm-gateway>) deployments. Sessions on Bedrock, Vertex AI, Foundry, and Claude Platform on AWS do not receive them, so use `availableModels` on those providers instead.
+Organization admins on Claude Enterprise plans restrict which models members can run by disabling individual models in the claude.ai admin console. This restriction is delivered with the account’s entitlements when Claude Code authenticates, separate from any `availableModels` list in settings, and the server enforces the same restriction independently when a session is created. Requires Claude Code v2.1.187 or later. The restriction applies when a member signs in or uses their own API key. Organization-scoped credentials, such as organization service keys, are not tied to a user, so the restriction does not apply to them. The Claude Console has no model restriction control. Organizations without a Claude Enterprise plan, including those whose members authenticate through the Anthropic API, restrict models with `availableModels` in [managed settings](</docs/en/settings#settings-files>) instead, adding `enforceAvailableModels` to cover the Default option. These settings are enforced by Claude Code itself, not by the server. A restricted model is hidden from the `/model` picker. Selecting it by name with `--model`, the `ANTHROPIC_MODEL` environment variable, or the `model` setting shows the notice `Model "<name>" is restricted by your organization's settings. Using <model> instead.` and the session starts on an allowed model. Typing `/model <name>` for a restricted model is rejected with `Model '<name>' is restricted by your organization's settings. Run /model to choose a different model.` and the session keeps its current model. Restrictions apply org-wide or per role:
+
+ * Disabling a model at the organization level removes it for every member.
+ * Role-level access grants different models to different custom roles, and a member who holds several roles can use any model that one of their roles grants.
+ * Haiku models are always available and can’t be disabled, so every member keeps at least one usable model.
+ * An access change takes effect on new requests within about a minute; the `/model` picker reflects it the next time a session starts.
+
+Both restrictions apply together: a model is selectable only when it is permitted by `availableModels` and not restricted by the organization. Organization restrictions are delivered to sessions on the Anthropic API and [LLM gateway](</docs/en/llm-gateway>) deployments. Sessions on Bedrock, Vertex AI, Foundry, and Claude Platform on AWS do not receive them, so use `availableModels` on those providers instead.
+
+##
+
+
+
+Organization default model
+
+Organization admins on Claude Enterprise plans can set a default model for Claude Code members from the claude.ai admin console, for the whole organization or per custom role. When one is set, the Default option resolves to that model instead of the account-type default. Requires Claude Code v2.1.196 or later. The Default row in the `/model` picker shows the organization default’s name with the label Org default. The label reads Org default whether the admin set the default for the whole organization or for your role. A role default covers members of that custom role and takes precedence over the organization-wide default; when several of your roles set different defaults, the most capable model applies. The organization default is a starting point, not a restriction, and any other model selection takes precedence over it:
+
+ * the `--model` flag and the `ANTHROPIC_MODEL` environment variable
+ * a `model` value in [managed settings](</docs/en/settings#settings-files>) or supplied through `--settings`
+ * a `model` value in your user, project, or local settings, including a model you save with `/model`
+
+Admins can also configure the organization default to override user selection. With override on, it takes precedence over the `model` value in user, project, and local settings, so a model you save with `/model` applies for the current session and the organization default returns on the next launch. When your selection differs, `/model` shows `Your organization's default (<model>) applies on restart`. The `--model` flag, `ANTHROPIC_MODEL`, managed settings, and `--settings` still take precedence even with override on. Override is available to a limited set of organizations; ask your Anthropic account team about availability. To limit which models members can select, use organization model restrictions or `availableModels` instead. Claude Code reads the organization default once at startup, so a default the admin changes mid-session takes effect on the next launch. When the organization default doesn’t override user selection, the first interactive launch after the admin changes it clears the `model` key from your user settings once, so the new default applies. It changes nothing else in the file, and a model you save with `/model` after that launch is kept. The organization default passes through the same restriction checks as any other Default model before it is adopted:
+
+ * `availableModels` on its own never constrains the Default option, so an organization default outside the allowlist still applies. When `enforceAvailableModels` is also set, an organization default outside the allowlist is remapped to the first allowlist entry, like any other Default
+ * an organization default that organization model restrictions deny for your account is replaced by the newest allowed model in its family, or a lower-cost family when every version of it is restricted
+ * an organization default that isn’t available to your account at all, such as Fable 5 under [zero data retention](</docs/en/zero-data-retention>), is skipped, and the Default option resolves to the account-type default
+
+As of v2.1.199, when the organization default is a different model family from your account type’s usual default, the `/model` picker keeps a separate row for that usual family, so you can still switch to it for a session. In v2.1.196 through v2.1.198 that row is missing from the picker. The organization default is delivered to sessions authenticated with the Anthropic API. Sessions on [LLM gateway](</docs/en/llm-gateway>) deployments, Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and Claude Platform on AWS don’t receive it. To set a default on those deployments, use the `model` key in [managed settings](</docs/en/settings#settings-files>) instead.
+
+##
+
+
+
+Organization effort limits
+
+Organization admins on Claude Enterprise plans can set a maximum effort level per model for each custom role, alongside role-level organization model restrictions. Levels above the cap aren’t offered in the `/effort` picker, and naming a higher level with `--effort` or `/effort` runs at the cap instead. In interactive sessions and plain-text `--print` runs, a warning names the requested and applied levels; with `json` or `stream-json` output or in background agents, the clamp applies silently. Caps are per model, so switching models can change which levels are available. When several of your roles grant the same model, the least restrictive cap applies. Requires Claude Code v2.1.195 or later. Effort limits are delivered together with organization model restrictions and follow the same provider availability: sessions on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and Claude Platform on AWS don’t receive them.
##
@@ -223,7 +258,7 @@
* **Pro, Team Standard, and Enterprise subscription seats** : defaults to Sonnet 5
* **Bedrock, Vertex, and Foundry** : defaults to Sonnet 4.5
-Enterprise pay-as-you-go means an Enterprise organization billed by usage rather than by subscription seat. When managed settings enforce the allowlist for the Default model and the account-type default is not in `availableModels`, `default` resolves to the enforced Default instead of the account-type default above. Fable 5 is not the default model on any account type. Sessions use Fable 5 only after you choose it, with `/model fable`, a `model` setting, or the `best` alias where Fable 5 is available. Choosing it with `/model` saves it as the selected model in your user settings, so later sessions start on Fable 5 until you change models.
+Enterprise pay-as-you-go means an Enterprise organization billed by usage rather than by subscription seat. When an admin has set an organization default model, `default` resolves to that model instead of the account-type default above. Requires Claude Code v2.1.196 or later. When managed settings enforce the allowlist for the Default model and the account-type default is not in `availableModels`, `default` resolves to the enforced Default instead of the account-type default above. When both apply, the organization default replaces the account-type default first and enforcement then applies to it: an allowlisted organization default is kept, while one outside the list resolves to the enforced Default. Fable 5 is not the default model on any account type. Sessions use Fable 5 only after you choose it, with `/model fable`, a `model` setting, or the `best` alias where Fable 5 is available. Choosing it with `/model` saves it as the selected model in your user settings, so later sessions start on Fable 5 until you change models.
###
@@ -323,7 +358,7 @@
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. 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. 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`.
####
--- a/monitoring-usage.md
+++ b/monitoring-usage.md
@@ -1124,7 +1124,7 @@
Detect retry exhaustion
-Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records how many attempts were made in total. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15. When the request exhausts all retries on a transient error, `attempt` equals one more than that effective limit: 11 by default, and never more than 16. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error.
+Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the total number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15; as of v2.1.199, `CLAUDE_CODE_RETRY_WATCHDOG` raises the default and removes the cap. When the request exhausts all retries on a transient error, `attempt` equals one more than that effective limit: 11 by default, and never more than 16 unless the watchdog is set. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error.
###
--- a/permission-modes.md
+++ b/permission-modes.md
@@ -189,6 +189,7 @@
* Force push, or pushing directly to `main`
* `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
* `terraform destroy`, `pulumi destroy`, `cdk destroy`, or `terragrunt destroy`, and applying a plan that destroys resources
Claude Code v2.1.195 and later block more categories by default. Several depend on [environment](</docs/en/auto-mode-config#define-trusted-infrastructure>) entries, such as sensitive remote targets and protected IaC scopes, that you can narrow to concrete names.
@@ -203,10 +204,17 @@
* Interactive shells or port-forwards into a sensitive remote target
* Opening a tunnel or reverse shell that makes a local service reachable from the public internet
* Printing a live credential or token into the transcript or a file
- * Accessing a PII or regulated-data location, or copying data out of one
- * Routing a package install around your internal package registry to a public registry
+ * Accessing a location listed as a sensitive data location in your [environment](</docs/en/auto-mode-config#define-trusted-infrastructure>), or copying data out of one. As of v2.1.198 this also blocks sending data from one to an audience the entry excludes
+ * Routing a package install around your internal package registry to a public registry. As of v2.1.198, this also applies when you’ve told Claude an internal registry or mirror exists in the conversation, not only when one is listed in your environment
* Running a command with a flag that disarms a safety guard, like `--insecure`
+ * Launching an autonomous agent loop that runs without human approval or a sandbox, such as one started with `--dangerously-skip-permissions` or `--no-sandbox`. As of v2.1.198 this also covers running a third-party agent or eval harness with isolation and per-action approval disabled, such as a runner started with `--yes-always`
* [Claude in Chrome](</docs/en/chrome>) browser actions that could send page content, cookies, or credentials off-origin
+
+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
+ * 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
**Allowed by default** :
@@ -224,7 +232,14 @@
* Sending data to the trusted domains, buckets, and services you list in [`environment`](</docs/en/auto-mode-config#define-trusted-infrastructure>). This covers data flow only, not destructive or credential operations on the same infrastructure
* [Claude in Chrome](</docs/en/chrome>) navigation to a trusted internal domain, localhost, or a URL you named
-Sandbox network access requests are routed through the classifier rather than allowed by default. Run `claude auto-mode defaults` to see the full rule lists. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure auto mode](</docs/en/auto-mode-config>).
+Sandbox network access requests are routed through the classifier rather than allowed by default. As of v2.1.198, the classifier reuses its verdict for a network host and port instead of re-running on every connection:
+
+ * An allow is reused until new content enters the conversation, at which point that host is checked again
+ * In the interactive CLI, a deny is dropped when the turn ends
+ * In [non-interactive mode](</docs/en/headless>) and Agent SDK sessions there is no turn boundary, so a deny is reused for the rest of the run
+ * Changing your permission mode or rules drops all cached verdicts
+
+Run `claude auto-mode defaults` to see the full rule lists. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure auto mode](</docs/en/auto-mode-config>).
###
@@ -248,7 +263,7 @@
1. Actions matching your [allow or deny rules](</docs/en/permissions#manage-permissions>) resolve immediately, except writes to protected paths, which route to the classifier even when an allow rule matches
2. Read-only actions and file edits in your working directory are auto-approved, except writes to protected paths
- 3. Everything else goes to the classifier
+ 3. Everything else goes to the classifier. As of v2.1.199, an MCP tool marked with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) skips the classifier and prompts you directly, so a consent step is never auto-approved on the tool author’s behalf
4. If the classifier blocks, Claude receives the reason and tries an alternative
On entering auto mode, broad allow rules that grant arbitrary code execution are dropped:
@@ -272,7 +287,7 @@
Cost and latency
-The classifier runs on a server-configured model that is independent of your `/model` selection, so switching models does not change classifier availability. Classifier calls count toward your token usage. Each check sends a portion of the transcript plus the pending action, adding a round-trip before execution. Reads and working-directory edits outside protected paths skip the classifier, so the overhead comes mainly from shell commands and network operations.
+The classifier runs on a server-configured model that is independent of your `/model` selection, so switching models does not change classifier availability. Classifier calls count toward your token usage. Each check sends a portion of the transcript plus the pending action, adding a round-trip before execution. Reads and working-directory edits outside protected paths skip the classifier, so the overhead comes mainly from shell commands and network operations. As of v2.1.198, a sandbox network verdict for a host and port is reused instead of re-classified on every connection, so repeated connections to the same host don’t each add a check. What the classifier blocks by default describes how long an allow and a deny last.
##
@@ -280,7 +295,7 @@
Allow only pre-approved tools with dontAsk mode
-`dontAsk` mode auto-denies every tool call that would otherwise prompt. Only actions matching your `permissions.allow` rules and [read-only Bash commands](</docs/en/permissions#read-only-commands>) can execute; explicit [`ask` rules](</docs/en/permissions#manage-permissions>) are denied rather than prompting. This makes the mode fully non-interactive for CI pipelines or restricted environments where you pre-define exactly what Claude may do. Cloud sessions on [Claude Code on the web](</docs/en/claude-code-on-the-web>) ignore `defaultMode: "dontAsk"`; see bypassPermissions for details. Set it at startup with the flag:
+`dontAsk` mode auto-denies every tool call that would otherwise prompt. The status bar shows `⏵⏵ don't ask on` while this mode is active. Only actions matching your `permissions.allow` rules and [read-only Bash commands](</docs/en/permissions#read-only-commands>) can execute; explicit [`ask` rules](</docs/en/permissions#manage-permissions>) are denied rather than prompting. As of v2.1.199, an MCP tool marked with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) is also denied in this mode even when an allow rule matches it, because its approval card needs an answer this mode never collects. This makes the mode fully non-interactive for CI pipelines or restricted environments where you pre-define exactly what Claude may do. Cloud sessions on [Claude Code on the web](</docs/en/claude-code-on-the-web>) ignore `defaultMode: "dontAsk"`; see bypassPermissions for details. Set it at startup with the flag:
claude --permission-mode dontAsk
@@ -290,7 +305,7 @@
Skip all checks with bypassPermissions mode
-`bypassPermissions` mode disables permission prompts and safety checks so tool calls execute immediately. As of v2.1.126 this includes writes to protected paths, which earlier versions still prompted for. Explicit [ask rules](</docs/en/permissions#manage-permissions>) still force a prompt in this mode, and removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, still prompt as a circuit breaker against model error. Only use this mode in isolated environments like containers, VMs, or dev containers without internet access, where Claude Code cannot damage your host system. You cannot enter `bypassPermissions` from a session that was started without one of the enabling flags; restart with one to enable it:
+`bypassPermissions` mode disables permission prompts and safety checks so tool calls execute immediately. As of v2.1.126 this includes writes to protected paths, which earlier versions still prompted for. Explicit [ask rules](</docs/en/permissions#manage-permissions>) still force a prompt in this mode, and removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, still prompt as a circuit breaker against model error. As of v2.1.199, MCP tools marked with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) also still prompt. Only use this mode in isolated environments like containers, VMs, or dev containers without internet access, where Claude Code cannot damage your host system. You cannot enter `bypassPermissions` from a session that was started without one of the enabling flags; restart with one to enable it:
claude --permission-mode bypassPermissions
--- a/plugins.md
+++ b/plugins.md
@@ -58,9 +58,11 @@
Create the plugin directory
-Every plugin lives in its own directory containing your skills, agents, or hooks, optionally alongside a `.claude-plugin/plugin.json` manifest. Create one now:
+Every plugin lives in its own directory containing your skills, agents, or hooks, optionally alongside a `.claude-plugin/plugin.json` manifest. The location doesn’t matter for this quickstart because you’ll point Claude Code at the directory with `--plugin-dir` in the test step. Create it anywhere convenient, such as a scratch folder or a projects directory:
mkdir my-first-plugin
+
+The remaining steps run from the parent directory and reference paths like `my-first-plugin/...` relative to it.
2
@@ -318,7 +320,7 @@
When a `--plugin-dir` plugin has the same name as an installed marketplace plugin, the local copy takes precedence for that session. This lets you test changes to a plugin you already have installed without uninstalling it first. The exception is plugins that managed settings force-enable or force-disable: `--plugin-dir` cannot override those. As you make changes to your plugin, run `/reload-plugins` to pick up the updates without restarting. This reloads plugins, skills, agents, hooks, plugin MCP servers, and plugin LSP servers. Test your plugin components:
* Try your skills with `/plugin-name:skill-name`
- * Check that agents appear in `/agents`
+ * Check that agents appear in `/context` under Custom Agents, or @-mention one by its scoped name
* Verify hooks work as expected
You can load multiple plugins at once by specifying the flag multiple times:
@@ -398,7 +400,7 @@
Create the plugin structure
-Create a new plugin directory:
+Create a new plugin directory in your project root, alongside the existing `.claude/` folder, so the relative `cp` paths in the next step resolve:
mkdir -p my-plugin/.claude-plugin
@@ -458,7 +460,7 @@
claude --plugin-dir ./my-plugin
-Test each component: run your commands, check agents appear in `/agents`, and verify hooks trigger correctly.
+Test each component: run your commands, check that agents appear in `/context`, and verify hooks trigger correctly.
###
--- a/plugins-reference.md
+++ b/plugins-reference.md
@@ -53,7 +53,7 @@
Plugin agents support `name`, `description`, `model`, `effort`, `maxTurns`, `tools`, `disallowedTools`, `skills`, `memory`, `background`, and `isolation` frontmatter fields. The only valid `isolation` value is `"worktree"`. For security reasons, `hooks`, `mcpServers`, and `permissionMode` are not supported for plugin-shipped agents. **Integration points** :
- * Agents appear in the `/agents` interface
+ * Agents appear in the [@-mention typeahead](</docs/en/sub-agents#invoke-subagents-explicitly>) under their scoped name, such as `my-plugin:code-reviewer`, once the plugin is enabled
* Claude can invoke agents automatically based on task context
* Agents can be invoked manually by users
* Plugin agents work alongside built-in Claude agents
--- a/python.md
+++ b/python.md
@@ -969,7 +969,7 @@
)
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
- * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1` to retry capacity errors indefinitely.
+ * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
--- a/sandboxing.md
+++ b/sandboxing.md
@@ -149,7 +149,7 @@
Protect credentials
-The `sandbox.credentials` setting declares credential files and environment variables that sandboxed commands must not access. Listed file paths are denied for reads inside the sandbox, the same restriction that `filesystem.denyRead` applies, and listed environment variables are unset before each sandboxed command runs. The dedicated `credentials` block keeps credential rules grouped with the environment variables to unset and separate from general filesystem rules. Requires Claude Code v2.1.187 or later. The example below blocks reads of the AWS credentials file and the SSH directory and removes `GITHUB_TOKEN` and `NPM_TOKEN` from the environment of sandboxed commands:
+The `sandbox.credentials` setting declares credential files and environment variables to protect from sandboxed commands. Each entry names a file path or an environment variable and a `mode`. The dedicated `credentials` block keeps credential rules grouped together and separate from general filesystem rules. Requires Claude Code v2.1.187 or later. For entries with `"mode": "deny"`, file paths are denied for reads inside the sandbox, the same restriction that `filesystem.denyRead` applies, and environment variables are unset before each sandboxed command runs. The example below blocks reads of the AWS credentials file and the SSH directory and removes `GITHUB_TOKEN` and `NPM_TOKEN` from the environment of sandboxed commands:
{
"sandbox": {
@@ -167,7 +167,33 @@
}
}
-Each entry carries `"mode": "deny"`, which is the only supported value. The explicit `mode` field keeps the schema forward-compatible with future modes. File paths follow the same [prefix rules](</docs/en/settings#sandbox-path-prefixes>) as `sandbox.filesystem.*` settings, and entries from every [settings scope](</docs/en/settings#settings-precedence>) are merged. Because the only mode is `deny`, any scope can add restrictions but none can remove them. There is no built-in credential deny list, so only the files and variables you list are restricted. The setting affects sandboxed Bash commands only. To strip Anthropic and cloud provider credentials from all subprocesses regardless of sandboxing, set [`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`](</docs/en/env-vars>).
+File entries support only `"mode": "deny"`. Environment variable entries also accept `"mode": "mask"`, described below. File paths follow the same [prefix rules](</docs/en/settings#sandbox-path-prefixes>) as `sandbox.filesystem.*` settings, and `deny` entries from every [settings scope](</docs/en/settings#settings-precedence>) are merged. A `deny` entry only ever narrows access, so any scope can add one, but no scope can remove one that another scope added. There is no built-in credential deny list, so only the files and variables you list are restricted. The setting affects sandboxed Bash commands only. To strip Anthropic and cloud provider credentials from all subprocesses regardless of sandboxing, set [`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`](</docs/en/env-vars>).
+
+####
+
+
+
+Mask environment variables
+
+`"mode": "mask"` protects a credential while keeping the tools that authenticate with it working. `deny` removes the variable entirely, which also breaks tools that need it, such as `gh` or `npm`. Requires Claude Code v2.1.199 or later. With `mask`, the sandboxed command sees a per-session sentinel value instead of the real one. When a request leaves the sandbox for one of the credential’s `injectHosts`, the sandbox proxy replaces the sentinel with the real value. The command and anything it logs never hold the real credential, but its requests still authenticate. The proxy substitutes the credential inside request contents, so it has to see them. Set [`network.tlsTerminate`](</docs/en/settings#sandbox-settings>) so the proxy terminates HTTPS itself. Without it, masking fails closed: the command still sees only the sentinel, but the sentinel reaches the server unchanged and authentication fails. Claude Code reports this misconfiguration at startup and in `/doctor`. The example below masks two tokens. `GH_TOKEN` is substituted only on requests to `api.github.com`, while `NPM_TOKEN` has no `injectHosts` and is substituted on requests to every host in `network.allowedDomains`. Each `injectHosts` entry must itself be covered by `network.allowedDomains`.
+
+ {
+ "sandbox": {
+ "enabled": true,
+ "network": {
+ "tlsTerminate": {},
+ "allowedDomains": ["*.github.com", "registry.npmjs.org"]
+ },
+ "credentials": {
+ "envVars": [
+ { "name": "GH_TOKEN", "mode": "mask", "injectHosts": ["api.github.com"] },
+ { "name": "NPM_TOKEN", "mode": "mask" }
+ ]
+ }
+ }
+ }
+
+Unlike `deny`, masking authorizes the proxy to send your real credential to the listed hosts, so it is honored only from settings you or your administrator control: user settings, managed settings, and the `--settings` CLI flag. `mask` entries, `network.tlsTerminate`, and [`credentials.allowPlaintextInject`](</docs/en/settings#sandbox-settings>) in a repository’s `.claude/settings.json` or `.claude/settings.local.json` are ignored. When the same variable is listed with `deny` in any scope, `deny` takes precedence.
##
@@ -204,7 +230,7 @@
* **Custom proxy support** : advanced users can implement custom rules on outgoing traffic
* **Comprehensive coverage** : restrictions apply to all scripts, programs, and subprocesses spawned by commands
-The built-in proxy enforces the allowlist based on the requested hostname and does not terminate or inspect TLS traffic. See Security limitations for the implications of this design, and Custom proxy configuration if your threat model requires TLS inspection.
+The built-in proxy enforces the allowlist based on the requested hostname and, by default, does not terminate or inspect TLS traffic. The experimental [`network.tlsTerminate`](</docs/en/settings#sandbox-settings>) setting, available in Claude Code v2.1.199 and later, makes the built-in proxy terminate TLS itself, which `mask` credential entries require. See Security limitations for the implications of the default, and Custom proxy configuration if your threat model requires TLS inspection.
###
@@ -364,7 +390,7 @@
Security limitations
- * **Network filtering** : the network filtering system operates by restricting the domains that processes are allowed to connect to. The built-in proxy does not terminate or perform TLS inspection on outbound traffic, so the contents of encrypted connections are not examined. You are responsible for ensuring that only trusted domains are allowed in your policy.
+ * **Network filtering** : the sandbox restricts which domains processes can connect to. By default the built-in proxy does not terminate or inspect TLS on outbound traffic, so the contents of encrypted connections are not examined. The experimental [`network.tlsTerminate`](</docs/en/settings#sandbox-settings>) setting terminates TLS at the proxy for `mask` credential substitution but does not add content filtering. You are responsible for ensuring that only trusted domains are allowed in your policy.
Allowing broad domains such as `github.com` can create paths for data exfiltration. Because the proxy makes its allow decision from the client-supplied hostname without inspecting TLS, code running inside the sandbox can potentially use [domain fronting](<https://en.wikipedia.org/wiki/Domain_fronting>) or similar techniques to reach hosts outside the allowlist. If your threat model requires stronger guarantees, configure a custom proxy that terminates TLS and inspects traffic, and install its CA certificate inside the sandbox. Stronger TLS-aware network isolation is an active area of development.
@@ -394,7 +420,7 @@
* **Built-in file tools** : Read, Edit, and Write use the permission system directly rather than running through the sandbox. See [permissions](</docs/en/permissions>).
* **Computer use** : when Claude opens apps and controls your screen, it runs on your actual desktop rather than in an isolated environment. Per-app permission prompts gate each application. See [computer use in the CLI](</docs/en/computer-use>) or [computer use in Desktop](</docs/en/desktop#let-claude-use-your-computer>).
- * **Environment variables** : sandboxed Bash commands inherit the parent process environment by default, including any credentials set there. Use `sandbox.credentials` to unset specific variables for sandboxed commands, or set [`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`](</docs/en/env-vars>) to strip Anthropic and cloud provider credentials from all subprocesses.
+ * **Environment variables** : sandboxed Bash commands inherit the parent process environment by default, including any credentials set there. Use `sandbox.credentials` to unset or mask specific variables for sandboxed commands, or set [`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`](</docs/en/env-vars>) to strip Anthropic and cloud provider credentials from all subprocesses.
* **Subagents** : [subagents](</docs/en/sub-agents>) run in the same process as the parent session and use the same sandbox configuration. Bash commands inside a subagent are sandboxed when sandboxing is enabled in the parent session.
Effective sandboxing requires both filesystem and network isolation. Without network isolation, a compromised agent could exfiltrate sensitive files like SSH keys. Without filesystem isolation, a compromised agent could backdoor system resources to gain network access. When you widen the defaults, check that an `allowWrite` path, a broad `allowedDomains` entry, or an `excludedCommands` exception does not undo a restriction on the other side.
--- a/server-managed-settings.md
+++ b/server-managed-settings.md
@@ -1,4 +1,4 @@
-Server-managed settings let organization Owners centrally configure Claude Code from [**Admin Settings > Claude Code > Managed settings**](<https://claude.ai/admin-settings/claude-code>) in the claude.ai console. Claude Code clients fetch these settings automatically when users authenticate with an organization OAuth login or a directly configured API key, on platforms where server-managed delivery is supported. See Platform availability. This approach is designed for organizations that do not have device management infrastructure in place, or that need to manage settings for users on unmanaged devices.
+Server-managed settings let organization Owners centrally configure Claude Code from [**Admin Settings > Claude Code > Managed settings**](<https://claude.ai/admin-settings/claude-code>) in the claude.ai console. Claude Code clients fetch these settings automatically when users authenticate with an organization OAuth login or a directly configured API key, on platforms where server-managed delivery is supported. See Platform availability. This approach is designed for organizations that don’t have device management infrastructure in place, or that need to manage settings for users on unmanaged devices.
Server-managed settings are available for [Claude for Teams](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=server_settings_teams#team-&-enterprise>) and [Claude for Enterprise](<https://anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=server_settings_enterprise>) customers.
@@ -28,7 +28,7 @@
**Server-managed settings**| Organizations without MDM, or users on unmanaged devices| Settings delivered from Anthropic’s servers at authentication time
**[Endpoint-managed settings](</docs/en/settings#settings-files>)**| Organizations with MDM or endpoint management| Settings deployed to devices via MDM configuration profiles, registry policies, or managed settings files
-If your devices are enrolled in an MDM or endpoint management solution, endpoint-managed settings provide stronger security guarantees because the settings file can be protected from user modification at the OS level. Endpoint-managed settings do not reach [cloud sessions](</docs/en/model-config#surface-coverage>), so organizations using Claude Code on the web should configure server-managed settings as well.
+If your devices are enrolled in an MDM or endpoint management solution, endpoint-managed settings provide stronger security guarantees because the settings file can be protected from user modification at the OS level. Endpoint-managed settings don’t reach [cloud sessions](</docs/en/model-config#surface-coverage>), so organizations using Claude Code on the web should configure server-managed settings as well.
##
@@ -134,7 +134,7 @@
Server-managed settings have the following limitations:
* Settings apply uniformly to all users in the organization. Per-group configurations are not yet supported.
- * A [`managed-mcp.json`](</docs/en/managed-mcp>) file cannot be distributed through server-managed settings. Deliver the `allowedMcpServers` and `deniedMcpServers` policy keys there instead.
+ * A [`managed-mcp.json`](</docs/en/managed-mcp>) file can’t be distributed through server-managed settings. Deliver the `allowedMcpServers` and `deniedMcpServers` policy keys there instead.
* Settings restricted to OS-level policy sources, such as `policyHelper` and `wslInheritsWindowsSettings`, are not honored. Deploy them through MDM or a system `managed-settings.json` file instead.
##
@@ -149,7 +149,7 @@
Settings precedence
-Server-managed settings and [endpoint-managed settings](</docs/en/settings#settings-files>) both occupy the highest tier in the Claude Code [settings hierarchy](</docs/en/settings#settings-precedence>). No other settings level can override them, including command line arguments. Within the managed tier, a configured [`policyHelper`](</docs/en/settings#compute-managed-settings-with-a-policy-helper>) preempts every other managed source, including server-managed settings: its output becomes the only managed configuration for the run. Otherwise the first source that delivers a non-empty configuration wins. Server-managed settings are checked first, then endpoint-managed settings. Sources do not merge: if server-managed settings deliver any keys at all, other endpoint-managed settings are ignored. One exception applies: a small set of [cross-source lock keys](</docs/en/settings#settings-precedence>), such as the sandbox allowlist locks, is honored when any admin-controlled managed source sets them; the user-writable HKCU registry tier is excluded. If server-managed settings deliver nothing, endpoint-managed settings apply. If you clear your server-managed configuration in the admin console with the intent of falling back to an endpoint-managed plist or registry policy, be aware that cached settings persist on client machines until the next successful fetch. Run `/status` to see which managed source is active.
+Server-managed settings and [endpoint-managed settings](</docs/en/settings#settings-files>) both occupy the highest tier in the Claude Code [settings hierarchy](</docs/en/settings#settings-precedence>). No other settings level can override them, including command line arguments. Within the managed tier, a configured [`policyHelper`](</docs/en/settings#compute-managed-settings-with-a-policy-helper>) preempts every other managed source, including server-managed settings: its output becomes the only managed configuration for the run. Otherwise, Claude Code uses the first source that delivers a non-empty configuration. Server-managed settings are checked first, then endpoint-managed settings. Sources don’t merge: if server-managed settings deliver any keys at all, other endpoint-managed settings are ignored. If server-managed settings deliver nothing, endpoint-managed settings apply. One exception applies: a small set of [cross-source lock keys](</docs/en/settings#settings-precedence>), such as the sandbox allowlist locks, is honored when any admin-controlled managed source sets them; the user-writable HKCU registry tier is excluded. If you clear your server-managed configuration in the admin console with the intent of falling back to an endpoint-managed plist or registry policy, be aware that cached settings persist on client machines until the next successful fetch. Run `/status` to see which managed source is active.
###
@@ -165,11 +165,17 @@
**Subsequent launches with cached settings:**
- * Cached settings apply immediately at startup
+ * Cached settings apply immediately at startup, except for the transport, routing, and authentication environment variables described below
* Claude Code fetches fresh settings in the background
- * Cached settings persist through network failures
-
-Claude Code applies settings updates automatically without a restart, except for advanced settings like OpenTelemetry configuration, which require a full restart to take effect.
+ * Cached settings persist through network failures. The withheld environment variables remain withheld until a fetch succeeds
+
+As of v2.1.198, Claude Code withholds three categories of variables in the cached `env` block until the server confirms the payload for the session. This keeps a cached proxy, certificate authority, endpoint, or credential value from redirecting, intercepting, or re-authenticating the settings fetch that confirms the payload. The hardening applies only to the server-fetched settings cache: [endpoint-managed settings](</docs/en/settings#settings-files>) deployed through MDM or `managed-settings.json` are unaffected. The withheld categories are:
+
+ * Proxy and TLS configuration, such as `HTTPS_PROXY`, `NODE_EXTRA_CA_CERTS`, and the mTLS client certificate variables `CLAUDE_CODE_CLIENT_CERT` and `CLAUDE_CODE_CLIENT_KEY`
+ * API routing and provider selection, including `ANTHROPIC_BASE_URL`, the provider selection variables such as `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_VERTEX`, and the provider endpoint URLs such as `ANTHROPIC_BEDROCK_BASE_URL`
+ * Authentication credentials, such as `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, and `CLAUDE_CODE_OAUTH_TOKEN`
+
+Every other key in the cached `env` block, such as telemetry and OpenTelemetry configuration, applies at startup as before. Once the fetch succeeds, the withheld variables apply for the rest of the session. If your organization needs a proxy to reach `api.anthropic.com`, set it in the shell environment or in [user settings](</docs/en/settings#settings-files>) rather than only in the managed `env` block. The first launch has no cache, so those sources were already required for the initial fetch. Claude Code applies settings updates automatically without a restart, except for advanced settings like OpenTelemetry configuration, which require a full restart to take effect.
###
@@ -197,7 +203,7 @@
"forceRemoteSettingsRefresh": true
}
-You can also set this key in an [endpoint-managed](</docs/en/settings#settings-files>) MDM profile or system `managed-settings.json` file to enforce fail-closed behavior on first launch, before any server payload has been delivered. As of v2.1.191, this flag is an exception to the precedence rule above: it is honored when set in any managed source even if a cached server-managed payload is also present, so an MDM-delivered value is not ignored when server-managed settings exist. The settings fetch also sends a `Cache-Control: no-cache` header so intermediate HTTP proxies do not serve a stale response. Before enabling this setting, ensure your network policies allow connectivity to `api.anthropic.com`. If that endpoint is unreachable, the CLI exits at startup and users cannot start Claude Code. As of v2.1.139, the `claude auth` subcommands such as `claude auth login` are exempt from this check, so users can re-authenticate when expired credentials are the reason the settings fetch fails.
+You can also set this key in an [endpoint-managed](</docs/en/settings#settings-files>) MDM profile or system `managed-settings.json` file to enforce fail-closed behavior on first launch, before any server payload has been delivered. As of v2.1.191, this flag is an exception to the precedence rule above: it is honored when set in any managed source even if a cached server-managed payload is also present, so an MDM-delivered value is not ignored when server-managed settings exist. The settings fetch also sends a `Cache-Control: no-cache` header so intermediate HTTP proxies don’t serve a stale response. Before enabling this setting, ensure your network policies allow connectivity to `api.anthropic.com`. If that endpoint is unreachable, the CLI exits at startup and users cannot start Claude Code. As of v2.1.139, the `claude auth` subcommands such as `claude auth login` are exempt from this check, so users can re-authenticate when expired credentials are the reason the settings fetch fails.
###
@@ -205,7 +211,7 @@
Security approval dialogs
-Certain settings that could pose security risks require explicit user approval before being applied:
+Certain settings that could pose security risks require explicit user approval before Claude Code applies them:
* **Shell command settings** : settings that execute shell commands
* **Custom environment variables** : variables not in the known safe allowlist
@@ -222,7 +228,7 @@
Platform availability
-Server-managed settings require a direct connection to `api.anthropic.com`, and delivery requires the session to authenticate with an organization OAuth login or a directly configured API key: keys returned by an [`apiKeyHelper`](</docs/en/settings#available-settings>) script do not trigger the settings fetch. Server-managed settings are not available when using third-party model providers:
+Server-managed settings require a direct connection to `api.anthropic.com`, and delivery requires the session to authenticate with an organization OAuth login or a directly configured API key. Keys returned by an [`apiKeyHelper`](</docs/en/settings#available-settings>) script don’t trigger the settings fetch. Server-managed settings are not available when using third-party model providers:
* Amazon Bedrock
* Google Vertex AI
@@ -250,11 +256,11 @@
Scenario| Behavior
---|---
-User edits the cached settings file| Tampered file applies at startup, but correct settings restore on the next server fetch
+User edits the cached settings file| Tampered file applies at startup, but correct settings restore on the next server fetch. As of v2.1.198, the transport, API-routing, and authentication environment variables in the `env` block are withheld until the server confirms the payload
User deletes the cached settings file| First-launch behavior occurs: settings fetch asynchronously with a brief unenforced window
User runs a modified Claude Code binary| A user who can run a modified client can bypass any client-side control
User runs an older Claude Code version| Versions that predate server-managed settings don’t fetch or apply them
-API is unavailable| Cached settings apply if available, otherwise managed settings are not enforced until the next successful fetch. With `forceRemoteSettingsRefresh: true`, the CLI exits instead of continuing, except for `claude auth` subcommands
+API is unavailable| Cached settings apply if available, otherwise managed settings are not enforced until the next successful fetch. As of v2.1.198, the transport, API-routing, and authentication environment variables in the cached `env` block are withheld on fetch failure; the rest of the cache still applies. With `forceRemoteSettingsRefresh: true`, the CLI exits instead of continuing, except for `claude auth` subcommands
User authenticates with a different organization| Settings are not delivered for accounts outside the managed organization
User configures a third-party model provider| Server-managed settings are bypassed. This includes setting `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_MANTLE`, `CLAUDE_CODE_USE_VERTEX`, `CLAUDE_CODE_USE_FOUNDRY`, `CLAUDE_CODE_USE_ANTHROPIC_AWS`, or a non-default `ANTHROPIC_BASE_URL`
Network traffic is intercepted or redirected| Disabled TLS validation or intercepted traffic can alter the settings the client receives
--- a/sessions.md
+++ b/sessions.md
@@ -81,7 +81,7 @@
/branch try-streaming-approach
-From the command line, combine `--continue` or `--resume` with `--fork-session`:
+If you omit the name, Claude Code names the new branch after the first prompt in the conversation. As of v2.1.198 this also applies after [compaction](</docs/en/how-claude-code-works#when-context-fills-up>); earlier versions fell back to the literal name `Branched conversation` instead of looking past the compaction summary to the original first prompt. From the command line, combine `--continue` or `--resume` with `--fork-session`:
claude --continue --fork-session
--- a/settings.md
+++ b/settings.md
@@ -248,7 +248,7 @@
`enableAllProjectMcpServers`| Automatically approve all MCP servers defined in project `.mcp.json` files. As of v2.1.196, `claude mcp list` and `claude mcp get` honor this key in an untrusted folder only from [settings files that aren’t checked into the repository](</docs/en/mcp#managing-your-servers>)| `true`
`enableArtifact`| Enable or disable the [Artifact](</docs/en/artifacts>) tool for this user. When unset, the default follows the feature’s [availability](</docs/en/artifacts#availability>) for your account. The **Artifacts** row in `/config` writes this key. A managed `disableArtifact` and your organization’s [admin setting](</docs/en/artifacts#manage-artifacts-for-your-organization>) take precedence, and the key is ignored in project and local settings (`.claude/settings.json`, `.claude/settings.local.json`), which a repository could otherwise commit. Requires Claude Code v2.1.196 or later| `true`
`enabledMcpjsonServers`| List of specific MCP servers from `.mcp.json` files to approve. As of v2.1.196, `claude mcp list` and `claude mcp get` honor this key in an untrusted folder only from [settings files that aren’t checked into the repository](</docs/en/mcp#managing-your-servers>)| `["memory", "github"]`
-`enforceAvailableModels`| Extend the `availableModels` allowlist to the Default model. When `true` in managed settings and `availableModels` is a non-empty array, the Default option falls back to the first allowlisted entry that is available, but only when the default model for the user’s account type is not in the allowlist; an allowlisted default is kept as-is. Has no effect when `availableModels` is unset or empty. See [Enforce the allowlist for the Default model](</docs/en/model-config#enforce-the-allowlist-for-the-default-model>). Requires Claude Code v2.1.175 or later| `true`
+`enforceAvailableModels`| Extend the `availableModels` allowlist to the Default model. When `true` in managed settings and `availableModels` is a non-empty array, the Default option falls back to the first allowlisted entry that is available, but only when the model Default would resolve to (the [organization default](</docs/en/model-config#organization-default-model>) when one applies, otherwise the account-type default) is not in the allowlist; an allowlisted default is kept as-is. Has no effect when `availableModels` is unset or empty. See [Enforce the allowlist for the Default model](</docs/en/model-config#enforce-the-allowlist-for-the-default-model>). Requires Claude Code v2.1.175 or later| `true`
`env`| Environment variables applied to every session and to subprocesses Claude Code spawns from it. As of v2.1.143, `NO_COLOR` and `FORCE_COLOR` set here are passed to subprocesses but do not change Claude Code’s own interface colors. Set those in your shell before launching `claude` to change interface colors. As of v2.1.195, identity variables that Claude Code’s hosting environments set, for example `CLAUDE_CODE_REMOTE` and `CLAUDE_CODE_ACCOUNT_UUID`, are ignored when set here| `{"FOO": "bar"}`
`fallbackModel`| Fallback model(s) to try in order when the primary model is overloaded or unavailable. Claude Code switches to the next available model in the chain for the rest of the turn and shows a notice. `"default"` expands to the default model. Chains are capped at three models; extra entries are ignored. Unlike most array settings, this key does not merge across settings files: the highest-precedence file that defines it supplies the entire chain. The [`--fallback-model`](</docs/en/cli-reference#cli-flags>) flag overrides this for one session. See [Fallback model chains](</docs/en/model-config#fallback-model-chains>)| `["claude-sonnet-5", "claude-haiku-4-5"]`
`fastModePerSessionOptIn`| When `true`, fast mode does not persist across sessions. Each session starts with fast mode off, requiring users to enable it with `/fast`. The user’s fast mode preference is still saved. See [Require per-session opt-in](</docs/en/fast-mode#require-per-session-opt-in>)| `true`
@@ -401,8 +401,10 @@
`filesystem.denyRead`| Paths where sandboxed commands cannot read. Arrays are merged across all settings scopes. Also merged with paths from `Read(...)` deny permission rules.| `["~/.aws/credentials"]`
`filesystem.allowRead`| Paths to re-allow reading within `denyRead` regions. Takes precedence over `denyRead`. Arrays are merged across all settings scopes. Use this to create workspace-only read access patterns.| `["."]`
`filesystem.allowManagedReadPathsOnly`| (Managed settings only) Only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources. Default: false| `true`
-`credentials.files`| Credential files or directories that sandboxed commands cannot read. Applies the same read block as `filesystem.denyRead`; the separate key keeps credential paths grouped with `credentials.envVars` and apart from general filesystem rules. Each entry is `{ "path": "...", "mode": "deny" }`. Paths use the same prefixes as `filesystem.*` settings. Arrays are merged across all settings scopes. Only `deny` is supported. Requires Claude Code v2.1.187 or later.| `[{ "path": "~/.aws/credentials", "mode": "deny" }]`
-`credentials.envVars`| Environment variables to unset before running sandboxed commands. Each entry is `{ "name": "...", "mode": "deny" }`. Arrays are merged across all settings scopes. Only `deny` is supported. Requires Claude Code v2.1.187 or later.| `[{ "name": "GITHUB_TOKEN", "mode": "deny" }]`
+`credentials.files`| Credential files or directories that sandboxed commands cannot read. Applies the same read block as `filesystem.denyRead`; the separate key keeps credential paths grouped with `credentials.envVars` and apart from general filesystem rules. Each entry is `{ "path": "...", "mode": "deny" }`, and `deny` is the only supported mode for files. Paths use the same prefixes as `filesystem.*` settings. Arrays are merged across all settings scopes. Requires Claude Code v2.1.187 or later.| `[{ "path": "~/.aws/credentials", "mode": "deny" }]`
+`credentials.envVars`| Environment variables to [protect from sandboxed commands](</docs/en/sandboxing#protect-credentials>). Each entry has a `name` and a `mode`; the name must start with a letter or underscore and contain only letters, digits, and underscores. `deny` removes the variable from the environment of sandboxed commands. Requires Claude Code v2.1.187 or later. `mask` replaces the variable with a per-session sentinel value inside the sandbox while the sandbox proxy substitutes the real value on outbound requests to that entry’s `injectHosts`; it requires `network.tlsTerminate` and Claude Code v2.1.199 or later. `mask` entries are only honored from user, managed, or CLI `--settings` settings, not from `.claude/settings.json` or `.claude/settings.local.json`. Arrays are merged across all settings scopes, and `deny` takes precedence when the same variable appears with both modes.| `[{ "name": "GITHUB_TOKEN", "mode": "deny" }]`
+`credentials.envVars[].injectHosts`| Hosts where the sandbox proxy substitutes the real value of a `mask` entry. Each host must also be covered by `network.allowedDomains`, either exactly or by a wildcard. When unset, the proxy substitutes the value on requests to every host in `network.allowedDomains`. Accepted but ignored when `mode` is `deny`. Requires Claude Code v2.1.199 or later. | `["api.github.com"]`
+`credentials.allowPlaintextInject`| Allow `mask` substitution on plain HTTP requests as well as TLS-terminated HTTPS. On plain HTTP the upstream identity is unverified and the credential travels in cleartext, so leave this off outside trusted test networks. Only honored from user, managed, or CLI `--settings` settings, not from `.claude/settings.json` or `.claude/settings.local.json`. Default: false. Requires Claude Code v2.1.199 or later. | `true`
`network.allowUnixSockets`| (macOS only) Unix socket paths accessible in sandbox. Ignored on Linux and WSL2, where the seccomp filter cannot inspect socket paths; use `allowAllUnixSockets` instead.| `["~/.ssh/agent-socket"]`
`network.allowAllUnixSockets`| Allow all Unix socket connections in sandbox. On Linux and WSL2 this is the only way to permit Unix sockets, since it skips the seccomp filter that otherwise blocks `socket(AF_UNIX, ...)` calls. Default: false| `true`
`network.allowLocalBinding`| Allow binding to localhost ports (macOS only). Default: false| `true`
@@ -412,6 +414,7 @@
`network.allowManagedDomainsOnly`| (Managed settings only) Only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Domains from user, project, and local settings are ignored. Non-allowed domains are blocked automatically without prompting the user. Denied domains are still respected from all sources. Default: false| `true`
`network.httpProxyPort`| HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy.| `8080`
`network.socksProxyPort`| SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy.| `8081`
+`network.tlsTerminate`| Experimental. Terminate TLS inside the sandbox proxy so it can read the contents of HTTPS requests. Required for `mask` [credential substitution](</docs/en/sandboxing#protect-credentials>). Set `{}` to generate an ephemeral certificate authority for the session, or set `caCertPath` and `caKeyPath` to use your own. Only honored from user, managed, or CLI `--settings` settings, not from `.claude/settings.json` or `.claude/settings.local.json`. Requires Claude Code v2.1.199 or later. | `{}`
`enableWeakerNestedSandbox`| Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false| `true`
`enableWeakerNetworkIsolation`| (macOS only) Allow access to the system TLS trust service (`com.apple.trustd.agent`) in the sandbox. Required for Go-based tools like `gh`, `gcloud`, and `terraform` to verify TLS certificates when using `httpProxyPort` with a MITM proxy and custom CA. **Reduces security** by opening a potential data exfiltration path. Default: false| `true`
`allowAppleEvents`| (macOS only) Allow sandboxed commands to send Apple Events. Required for `open`, `osascript`, and tools that open URLs in a browser, which otherwise fail with error `-600`. **Removes code-execution isolation.** Sandboxed commands can launch other applications unsandboxed with no user prompt; they can also send AppleScript commands to running applications such as Terminal, subject to the per-app macOS automation-consent prompt (TCC). Only honored from user, managed, or CLI settings, not from project settings. Default: false| `true`
@@ -622,7 +625,17 @@
1. **Managed settings** ([server-managed](</docs/en/server-managed-settings>), MDM/OS-level policies, or [managed settings](</docs/en/settings#settings-files>))
* Policies deployed by IT through server delivery, MDM configuration profiles, registry policies, or managed settings files
* Cannot be overridden by any other level, including command line arguments
- * Within the managed tier, precedence is: `policyHelper` output, which when configured is the only managed source used > remote (claude.ai [server-managed](</docs/en/server-managed-settings>) or [Claude apps gateway](</docs/en/claude-apps-gateway>)-delivered) > MDM/OS-level policies > file-based (`managed-settings.d/*.json` \+ `managed-settings.json`) > HKCU registry (Windows only). Only one managed source is used; sources do not merge across tiers, with one exception: the sandbox lock keys `sandbox.network.allowManagedDomainsOnly` and `sandbox.filesystem.allowManagedReadPathsOnly`, with their associated allowlists, `allowAllClaudeAiMcps`, and the sandbox binary paths `sandbox.bwrapPath` and `sandbox.socatPath` are honored when any admin-controlled managed source sets them; the user-writable HKCU tier is excluded. Within the file-based tier, drop-in files and the base file are merged together.
+ * Within the managed tier, only one source is used and the others are ignored rather than merged. Precedence, highest first:
+ * `policyHelper` output: when configured, this is the only managed source used
+ * Remote (claude.ai [server-managed](</docs/en/server-managed-settings>) or [Claude apps gateway](</docs/en/claude-apps-gateway>)-delivered)
+ * MDM/OS-level policies
+ * File-based (`managed-settings.d/*.json` and `managed-settings.json`, merged together)
+ * HKCU registry (Windows only)
+ * A few keys are exceptions, honored when any admin-controlled managed source sets them rather than only the winning source. The user-writable HKCU registry source is excluded. The exception keys are:
+ * the sandbox lock keys `sandbox.network.allowManagedDomainsOnly` and `sandbox.filesystem.allowManagedReadPathsOnly`, with their associated allowlists
+ * `allowAllClaudeAiMcps`
+ * the sandbox binary paths `sandbox.bwrapPath` and `sandbox.socatPath`
+ * [`forceRemoteSettingsRefresh`](</docs/en/server-managed-settings>)
* Embedding hosts such as Claude Desktop can supply policy via the SDK `managedSettings` option. By default this is ignored when an admin-deployed managed source is present: server-managed settings, an MDM or OS-level policy, or a managed settings file. The user-writable HKCU registry fallback does not count as an admin-deployed source. Administrators can opt in by setting `parentSettingsBehavior` to `"merge"`. The embedder’s values are filtered so they can tighten managed policy but not loosen it.
2. **Command line arguments**
* Temporary overrides for a specific session. JSON passed via `--settings <file-or-json>` merges with file-based settings using the same rules as the other layers: a key set here overrides the same key in local, project, or user settings, and omitting a key leaves the lower-layer value in place
--- a/setup.md
+++ b/setup.md
@@ -345,7 +345,7 @@
Install with npm
-You can also install Claude Code as a global npm package. The package requires [Node.js 18 or later](<https://nodejs.org/en/download>).
+You can also install Claude Code as a global npm package. As of v2.1.198, the npm package requires [Node.js 22 or later](<https://nodejs.org/en/download>). On an older Node.js version, npm prints an `EBADENGINE` warning during install rather than failing; the install completes and `claude` still runs, since the package downloads a native binary that doesn’t use your Node.js at runtime.
npm install -g @anthropic-ai/claude-code
--- a/skills.md
+++ b/skills.md
@@ -384,7 +384,7 @@
4. Write tests
5. Create a commit
-When you run `/fix-issue 123`, Claude receives “Fix GitHub issue 123 following our coding standards…” If you invoke a skill with arguments but the skill doesn’t include `$ARGUMENTS`, Claude Code appends `ARGUMENTS: <your input>` to the end of the skill content so Claude still sees what you typed. To access individual arguments by position, use `$ARGUMENTS[N]` or the shorter `$N`:
+When you run `/fix-issue 123`, Claude receives “Fix GitHub issue 123 following our coding standards…” If you invoke a skill with arguments but the skill doesn’t include `$ARGUMENTS`, Claude Code appends `ARGUMENTS: <your input>` to the end of the skill content so Claude still sees what you typed. You can also stack several skills at the start of one message. As of v2.1.199, typing `/code-review /fix-issue 123` loads both skills and passes the trailing text `123` as `$ARGUMENTS` to each of them. In earlier versions, only the first skill loaded and received `/fix-issue 123` as literal argument text. Claude Code expands the first skill plus up to five more stacked after it. Expansion stops at the first token that isn’t an inline user-invocable skill, so a skill that runs as a forked subagent or one whose arguments may themselves start with a slash command, such as `/loop`, also ends the run there; that token and everything after it become the argument text for every expanded skill. To access individual arguments by position, use `$ARGUMENTS[N]` or the shorter `$N`:
---
name: migrate-component
@@ -541,7 +541,7 @@
`"user-invocable-only"`| Hidden| Yes
`"off"`| Hidden| Hidden
-A skill that is absent from `skillOverrides` is treated as `"on"`. The example below collapses one skill to its name and turns another off entirely:
+As of v2.1.199, `"off"` also hides the skill from the command lists advertised to [Remote Control](</docs/en/remote-control>) clients and to [Agent SDK](</docs/en/agent-sdk/slash-commands>) callers, not only the terminal `/` menu. Invoking a hidden skill by its full name still returns the `skillOverrides` error instead of running it. A skill that is absent from `skillOverrides` is treated as `"on"`. The example below collapses one skill to its name and turns another off entirely:
{
"skillOverrides": {
Show diff (342 lines)
--- a/sub-agents.md
+++ b/sub-agents.md
@@ -10,7 +10,7 @@
* **Specialize behavior** with focused system prompts for specific domains
* **Control costs** by routing tasks to faster, cheaper models like Haiku
-Claude uses each subagent’s description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it. Claude Code includes several built-in subagents like **Explore** , **Plan** , and **general-purpose**. You can also create custom subagents to handle specific tasks.
+Claude uses each subagent’s description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it. Claude Code includes several built-in subagents such as Explore, Plan, and general-purpose. You can also create custom subagents to handle specific tasks.
##
@@ -30,11 +30,11 @@
A fast, read-only agent optimized for searching and analyzing codebases.
- * **Model** : Haiku, which is fast and low-latency
+ * **Model** : inherits from the main conversation, capped at Opus on the Claude API, so Explore never runs on a more expensive model than the one you already chose for the session
* **Tools** : read-only tools; Write and Edit are denied
* **Purpose** : file discovery, code search, codebase exploration
-Claude delegates to Explore when it needs to search or understand a codebase without making changes. This keeps exploration results out of your main conversation context.When invoking Explore, Claude specifies a thoroughness level: **quick** for targeted lookups, **medium** for balanced exploration, or **very thorough** for comprehensive analysis.
+As of v2.1.198, Explore inherits the main conversation’s model instead of always running on Haiku. On the Claude API, the inherited model is capped at Opus: a main conversation on a higher tier runs Explore on Opus, and a main conversation on Sonnet or Haiku runs Explore on that same model. On any other provider, such as [Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or Claude Platform on AWS](</docs/en/third-party-integrations>), Explore inherits the main conversation’s model directly.A user or project subagent named `Explore` overrides the built-in and keeps its own `model` field, so define one with `model: haiku` to keep exploration on a lower-cost model.Claude delegates to Explore when it needs to search or understand a codebase without making changes. This keeps exploration results out of your main conversation context.When invoking Explore, Claude specifies a thoroughness level: **quick** for targeted lookups, **medium** for balanced exploration, or **very thorough** for comprehensive analysis.
A research agent used during [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) to gather context before presenting a plan.
@@ -59,10 +59,11 @@
statusline-setup| Sonnet| When you run `/statusline` to configure your status line
claude-code-guide| Haiku| When you ask questions about Claude Code features
-Built-in subagents are always registered in interactive sessions. To restrict them:
+Built-in subagents are registered by default in interactive sessions. To restrict them:
* To block a specific built-in type, add it to `permissions.deny` as shown in Disable specific subagents.
* To prevent Claude from delegating to any subagent, deny the `Agent` tool itself with [`permissions.deny`](</docs/en/permissions#tool-specific-permission-rules>).
+ * To remove only the built-in `Explore` and `Plan` subagents, set [`CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1`](</docs/en/env-vars>). Claude reads and explores files directly instead of delegating to them. Requires Claude Code v2.1.198 or later.
* In [non-interactive mode](</docs/en/headless>) and the [Agent SDK](</docs/en/agent-sdk/overview>), set [`CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS=1`](</docs/en/env-vars>) to remove all built-in types and supply only your own.
Beyond these built-in subagents, you can create your own with custom prompts, tool restrictions, permission modes, hooks, and skills. The following sections show how to get started and customize subagents.
@@ -73,69 +74,52 @@
Quickstart: create your first subagent
-Subagents are defined in Markdown files with YAML frontmatter. You can create them manually or use the `/agents` command. This walkthrough guides you through creating a user-level subagent with the `/agents` command. The subagent reviews code and suggests improvements for the codebase.
+Subagents are Markdown files with YAML frontmatter. To create one, ask Claude to write it for you, or write the file yourself. As of v2.1.198, the `/agents` command no longer opens the interactive creation wizard; running it prints a reminder to ask Claude or edit `.claude/agents/` directly. Subagent files, frontmatter fields, and the `.claude/agents/` and `~/.claude/agents/` locations are unchanged; only the terminal wizard is removed. This walkthrough creates a user-level subagent that reviews code and suggests improvements.
1
-Open the subagents interface
-
-In Claude Code, run:
-
- /agents
+Ask Claude to create the subagent
+
+In Claude Code, describe the subagent you want and where to save it:
+
+ Create a personal code-improver subagent in ~/.claude/agents/ that scans
+ files and suggests improvements for readability, performance, and best
+ practices. It should explain each issue, show the current code, and
+ provide an improved version. Make it read-only and have it use Sonnet.
+
+Claude writes the file with a `name`, a `description`, a `tools` list, a `model`, and a system prompt.
2
-Choose a location
-
-Switch to the **Library** tab, select **Create new agent** , then choose **Personal**. This saves the subagent to `~/.claude/agents/` so it’s available in all your projects.
+Review the file
+
+Open `~/.claude/agents/code-improver.md` and confirm the frontmatter matches what you asked for. The result looks like this:
+
+ ---
+ name: code-improver
+ description: Scans files and suggests improvements for readability, performance, and best practices. Use after writing or modifying code.
+ tools: Read, Grep, Glob
+ model: sonnet
+ ---
+
+ You are a code improvement specialist. For each issue you find, explain
+ the problem, show the current code, and provide an improved version.
+
+Because the file lives in `~/.claude/agents/`, the subagent is available in every project on your machine. To scope it to one project instead, move it to that project’s `.claude/agents/` directory. Choose the subagent scope compares the two.
3
-Generate with Claude
-
-Select **Generate with Claude**. When prompted, describe the subagent:
-
- A code improvement agent that scans files and suggests improvements
- for readability, performance, and best practices. It should explain
- each issue, show the current code, and provide an improved version.
-
-Claude generates the identifier, description, and system prompt for you.
-
-4
-
-Select tools
-
-For a read-only reviewer, deselect everything except **Read-only tools**. If you keep all tools selected, the subagent inherits all tools available to the main conversation.
-
-5
-
-Select model
-
-Choose which model the subagent uses. For this example agent, select **Sonnet** , which balances capability and speed for analyzing code patterns.
-
-6
-
-Choose a color
-
-Pick a background color for the subagent. This helps you identify which subagent is running in the UI.
-
-7
-
-Configure memory
-
-Select **User scope** to give the subagent a persistent memory directory at `~/.claude/agent-memory/`. The subagent uses this to accumulate insights across conversations, such as codebase patterns and recurring issues. Select **None** if you don’t want the subagent to persist learnings.
-
-8
-
-Save and try it out
-
-Review the configuration summary. Press `s` or `Enter` to save, or press `e` to save and edit the file in your editor. The subagent is available immediately. Try it:
+Try it out
+
+Ask Claude to delegate to the new subagent:
Use the code-improver agent to suggest improvements in this project
-Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions.
-
-You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements. You can also create subagents manually as Markdown files, define them via CLI flags, or distribute them through plugins. The following sections cover all configuration options.
+Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions.If Claude can’t find the new subagent, restart Claude Code and try again. This happens only when `~/.claude/agents/` didn’t exist before the session started, because a running session doesn’t detect a newly created `agents` directory.
+
+You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements. You can also write subagent files by hand, define them via CLI flags, or distribute them through plugins. The following sections cover all configuration options.
+
+On Claude Code v2.1.197 and earlier, `/agents` opens an interactive wizard with a **Running** tab that lists live subagents and a **Library** tab for creating, editing, and deleting them.
##
@@ -143,21 +127,7 @@
Configure subagents
-###
-
-
-
-Use the /agents command
-
-The `/agents` command opens a tabbed interface for managing subagents. The **Running** tab lists live and recently finished subagents and lets you open or stop them. The **Library** tab lets you:
-
- * View all available subagents (built-in, user, project, and plugin)
- * Create new subagents with guided setup or Claude generation
- * Edit existing subagent configuration and tool access
- * Delete custom subagents
- * See which subagents are active when duplicates exist
-
-This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly.
+A subagent’s file location determines who it’s available to, and its frontmatter determines what it can do. This section covers where subagent files live and every field they support.
###
@@ -165,14 +135,14 @@
Choose the subagent scope
-Subagents are Markdown files with YAML frontmatter. Store them in different locations depending on scope. When multiple subagents share the same name, Claude Code uses the one from the higher-priority location.
+Store subagent files in different locations depending on scope. When multiple subagents share the same name, Claude Code uses the one from the higher-priority location.
Location| Scope| Priority| How to create
---|---|---|---
Managed settings| Organization-wide| 1 (highest)| Deployed via [managed settings](</docs/en/settings>)
`--agents` CLI flag| Current session| 2| Pass JSON when launching Claude Code
-`.claude/agents/`| Current project| 3| Interactive or manual
-`~/.claude/agents/`| All your projects| 4| Interactive or manual
+`.claude/agents/`| Current project| 3| Ask Claude, or create the file manually
+`~/.claude/agents/`| All your projects| 4| Ask Claude, or create the file manually
Plugin’s `agents/` directory| Where plugin is enabled| 5 (lowest)| Installed with [plugins](</docs/en/plugins>)
**Project subagents** (`.claude/agents/`) are ideal for subagents specific to a codebase. Check them into version control so your team can use and improve them collaboratively. Project subagents are discovered by walking up from the current working directory, so every `.claude/agents/` between there and the repository root is scanned. As of v2.1.178, when more than one of these nested directories defines the same `name`, Claude Code uses the definition closest to the working directory. Directories added with `--add-dir` are also scanned: a `.claude/agents/` folder inside an added directory loads alongside project subagents. See [Additional directories](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) for which other configuration types load from `--add-dir`. To share subagents across projects without `--add-dir`, use `~/.claude/agents/` or a [plugin](</docs/en/plugins>). **User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects. Claude Code scans `.claude/agents/` and `~/.claude/agents/` recursively, so you can organize definitions into subfolders such as `agents/review/` or `agents/research/`. The subdirectory path doesn’t affect how a subagent is identified or invoked, because identity comes only from the `name` frontmatter field. Keep `name` values unique across the whole tree: if two files within one scope declare the same name, Claude Code loads only one of them. As of v2.1.196, running `/doctor` reports same-scope duplicate agent names and shows which definition is active. Plugin `agents/` directories are also scanned recursively. Unlike project and user scopes, a subfolder inside a plugin’s `agents/` directory becomes part of the scoped identifier: a file at `agents/review/security.md` in plugin `my-plugin` registers as `my-plugin:review:security`. **CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren’t saved to disk, making them useful for quick testing or automation scripts. You can define multiple subagents in a single `--agents` call:
@@ -209,7 +179,7 @@
}
'@
-The `--agents` flag accepts JSON with the same frontmatter fields as file-based subagents: `description`, `prompt`, `tools`, `disallowedTools`, `model`, `permissionMode`, `mcpServers`, `hooks`, `maxTurns`, `skills`, `initialPrompt`, `memory`, `effort`, `background`, `isolation`, and `color`. Use `prompt` for the system prompt, equivalent to the markdown body in file-based subagents. **Managed subagents** are deployed by organization administrators. Place markdown files in `.claude/agents/` inside the [managed settings directory](</docs/en/settings#settings-files>), using the same frontmatter format as project and user subagents. Managed definitions take precedence over project and user subagents with the same name. **Plugin subagents** come from [plugins](</docs/en/plugins>) you’ve installed. They appear in `/agents` alongside your custom subagents. See the [plugin components reference](</docs/en/plugins-reference#agents>) for details on creating plugin subagents.
+The `--agents` flag accepts JSON with the same frontmatter fields as file-based subagents: `description`, `prompt`, `tools`, `disallowedTools`, `model`, `permissionMode`, `mcpServers`, `hooks`, `maxTurns`, `skills`, `initialPrompt`, `memory`, `effort`, `background`, `isolation`, and `color`. Use `prompt` for the system prompt, equivalent to the markdown body in file-based subagents. **Managed subagents** are deployed by organization administrators. Place markdown files in `.claude/agents/` inside the [managed settings directory](</docs/en/settings#settings-files>), using the same frontmatter format as project and user subagents. Managed definitions take precedence over project and user subagents with the same name. **Plugin subagents** come from [plugins](</docs/en/plugins>) you’ve installed. They load alongside your custom subagents and appear in the @-mention typeahead under their scoped name. See the [plugin components reference](</docs/en/plugins-reference#agents>) for details on creating plugin subagents.
For security reasons, plugin subagents don’t support the `hooks`, `mcpServers`, or `permissionMode` frontmatter fields. These fields are ignored when loading agents from a plugin. If you need them, copy the agent file into `.claude/agents/` or `~/.claude/agents/`. You can also add rules to [`permissions.allow`](</docs/en/settings#permission-settings>) in `settings.json` or `settings.local.json`, but these rules apply to the entire session, not only the plugin subagent.
@@ -223,7 +193,10 @@
Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:
-Subagents are loaded at session start. If you add or edit a subagent file directly on disk, restart your session to load it. Subagents created through the `/agents` interface take effect immediately without a restart.
+Claude Code watches `~/.claude/agents/` and `.claude/agents/`. When you add or edit a subagent file on disk, or ask Claude to write one for you, Claude Code detects the change within a few seconds and the next delegation uses the updated definition, with no restart needed.Two cases still need a restart:
+
+ * The watcher covers only directories that existed when the session started, so after creating a scope’s first agent file in a new `agents` directory, restart to load it.
+ * Sessions started with `--disable-slash-commands` don’t watch these directories at all.
---
name: code-reviewer
@@ -258,7 +231,7 @@
`mcpServers`| No| [MCP servers](</docs/en/mcp>) available to this subagent. Each entry is either a server name referencing an already-configured server (e.g., `"slack"`) or an inline definition with the server name as key and a full [MCP server config](</docs/en/mcp#installing-mcp-servers>) as value. Ignored for plugin subagents
`hooks`| No| Lifecycle hooks scoped to this subagent. Ignored for plugin subagents
`memory`| No| Persistent memory scope: `user`, `project`, or `local`. Enables cross-session learning
-`background`| No| Set to `true` to always run this subagent as a background task. Default: `false`
+`background`| No| Set to `true` to always run this subagent as a background task, even when Claude needs its result right away. When unset, Claude chooses, and as of v2.1.198 it runs subagents in the background by default
`effort`| No| Effort level when this subagent is active. Overrides the session effort level. Default: inherits from session. Options: `low`, `medium`, `high`, `xhigh`, `max`; available levels depend on the model
`isolation`| No| Set to `worktree` to run the subagent in a temporary [git worktree](</docs/en/worktrees>), giving it an isolated copy of the repository branched by default from your [default branch](</docs/en/worktrees#choose-the-base-branch>) rather than the parent session’s `HEAD`. The worktree is automatically cleaned up if the subagent makes no changes
`color`| No| Display color for the subagent in the task list and transcript. Accepts `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, or `cyan`
@@ -284,7 +257,7 @@
3. The subagent definition’s `model` frontmatter
4. The main conversation’s model
-As of v2.1.196, setting `CLAUDE_CODE_SUBAGENT_MODEL` to `inherit` is the same as leaving it unset: resolution continues with the per-invocation `model` parameter, then the frontmatter. In earlier versions, `inherit` forced subagents onto the main conversation’s model and ignored both of those sources. The environment variable, per-invocation parameter, and frontmatter values are checked against your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist. A value that resolves to an excluded model is not used and the subagent runs on the inherited model instead.
+As of v2.1.196, setting `CLAUDE_CODE_SUBAGENT_MODEL` to `inherit` is the same as leaving it unset: resolution continues with the per-invocation `model` parameter, then the frontmatter. In earlier versions, `inherit` forced subagents onto the main conversation’s model and ignored both of those sources. Claude Code checks the environment variable, per-invocation parameter, and frontmatter values against your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist. It skips a value that resolves to an excluded model and runs the subagent on the inherited model instead. As of v2.1.198, subagents also inherit the main conversation’s [extended thinking](</docs/en/model-config#extended-thinking>) configuration: if thinking is on in your session, it’s on for the subagent, and if it’s off, it stays off. There is no per-subagent thinking setting. Before v2.1.198, subagents ran with extended thinking disabled regardless of the main conversation’s setting.
###
@@ -300,7 +273,7 @@
Available tools
-Subagents inherit the [internal tools](</docs/en/tools-reference>) and MCP tools available in the main conversation by default. The following tools depend on the main conversation’s UI or session state and are not available to subagents, even when listed in the `tools` field:
+Subagents inherit the [internal tools](</docs/en/tools-reference>) and MCP tools available in the main conversation by default. The following tools depend on the main conversation’s UI or session state and aren’t available to subagents, even when listed in the `tools` field:
* `AskUserQuestion`
* `EnterPlanMode`
@@ -308,7 +281,7 @@
* `ScheduleWakeup`
* `WaitForMcpServers`
-To restrict tools, use either the `tools` field (allowlist) or the `disallowedTools` field (denylist). This example uses `tools` to exclusively allow Read, Grep, Glob, and Bash. The subagent can’t edit files, write files, or use any MCP tools:
+To restrict tools, use the `tools` field as an allowlist or the `disallowedTools` field as a denylist. This example uses `tools` to allow only Read, Grep, Glob, and Bash. The subagent can’t edit files, write files, or use any MCP tools:
---
name: safe-researcher
@@ -386,7 +359,7 @@
Use the Playwright tools to navigate, screenshot, and interact with pages.
-Inline definitions use the same schema as `.mcp.json` server entries (`stdio`, `http`, `sse`, `ws`), keyed by the server name. To keep an MCP server out of the main conversation entirely and avoid its tool descriptions consuming context there, define it inline here rather than in `.mcp.json`. The subagent gets the tools; the parent conversation doesn’t. As of v2.1.153, the MCP restrictions that apply to the main session also cover servers declared in subagent frontmatter:
+Inline definitions use the same schema as `.mcp.json` server entries, keyed by the server name, and support the `stdio`, `http`, `sse`, and `ws` types. To keep an MCP server out of the main conversation entirely and avoid its tool descriptions consuming context there, define it inline here rather than in `.mcp.json`. The subagent gets the tools; the parent conversation doesn’t. As of v2.1.153, the MCP restrictions that apply to the main session also cover servers declared in subagent frontmatter:
* [`--strict-mcp-config`](</docs/en/cli-reference>) and [`--bare`](</docs/en/cli-reference>)
* [Enterprise managed MCP configuration](</docs/en/managed-mcp>)
@@ -460,7 +433,7 @@
---|---|---
`user`| `~/.claude/agent-memory/<name-of-agent>/`| the subagent should remember learnings across all projects
`project`| `.claude/agent-memory/<name-of-agent>/`| the subagent’s knowledge is project-specific and shareable via version control
-`local`| `.claude/agent-memory-local/<name-of-agent>/`| the subagent’s knowledge is project-specific but should not be checked into version control
+`local`| `.claude/agent-memory-local/<name-of-agent>/`| the subagent’s knowledge is project-specific but shouldn’t be checked into version control
When memory is enabled:
@@ -470,7 +443,7 @@
##### Persistent memory tips
- * `project` is the recommended default scope. It makes subagent knowledge shareable via version control. Use `user` when the subagent’s knowledge is broadly applicable across projects, or `local` when the knowledge should not be checked into version control.
+ * `project` is the recommended default scope. It makes subagent knowledge shareable via version control.
* Ask the subagent to consult its memory before starting work: “Review this PR, and check your memory for patterns you’ve seen before.”
* Ask the subagent to update its memory after completing a task: “Now that you’re done, save what you learned to your memory.” Over time, this builds a knowledge base that makes the subagent more effective.
* Include memory instructions directly in the subagent’s markdown file so it proactively maintains its own knowledge base:
@@ -690,12 +663,25 @@
* **Foreground subagents** block the main conversation until complete. Permission prompts are passed through to you as they come up.
* **Background subagents** run concurrently while you continue working. As of v2.1.186, when a background subagent reaches a tool call that needs permission, the prompt surfaces in your main session and names the subagent that is asking. Approve to let the subagent continue, or press Esc to deny that one tool call without stopping the subagent. Before v2.1.186, background subagents auto-denied any tool call that would have prompted.
-Claude decides whether to run subagents in the foreground or background based on the task. You can also:
-
- * Ask Claude to “run this in the background”
+As of v2.1.198, subagents run in the background by default. Claude runs a subagent in the foreground when it needs the result before continuing. The default changes where a subagent runs, not what it’s allowed to do: background subagents still surface every permission prompt in your main session. Before v2.1.198, Claude chose between foreground and background based on the task. You can also steer this yourself:
+
+ * Ask Claude to run a task in the background or in the foreground
* Press **Ctrl+B** to background a running task
-To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](</docs/en/env-vars>). When `CLAUDE_CODE_FORK_SUBAGENT` is set to `1`, every subagent spawn runs in the background regardless of the `background` field. Permission prompts from these background subagents surface in your main session as described above.
+To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](</docs/en/env-vars>). When `CLAUDE_CODE_FORK_SUBAGENT` is set to `1`, every subagent spawn runs in the background and the frontmatter `background` field has no effect, because fork mode removes the `run_in_background` parameter from the `Agent` tool. `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` takes precedence over fork mode and keeps subagent spawns in the foreground.
+
+###
+
+
+
+API errors in subagents
+
+As of v2.1.199, a subagent whose run ends on an API error, such as a usage limit or a repeated server error, reports that failure back to Claude instead of returning the error text as if it were the subagent’s findings. What Claude receives depends on where the subagent ran:
+
+ * **Foreground** : if a rate limit, overload, or server error cuts off a subagent that already produced output, the Agent tool returns that partial output with a note that the subagent was cut off and didn’t finish its task. Otherwise the tool call fails with [`Agent terminated early due to an API error`](</docs/en/errors#agent-terminated-early-due-to-an-api-error>), followed by the error detail.
+ * **Background** : the subagent is marked failed, and the message Claude receives when it ends names the API error and includes the subagent’s last output, so partial work isn’t lost.
+
+Once the underlying API error clears, ask Claude to retry the task or resume the subagent.
###
@@ -766,7 +752,7 @@
Spawn nested subagents
-As of Claude Code v2.1.172, a subagent can spawn its own subagents. Use this when a delegated task itself splits into parallel subtasks, such as a reviewer subagent that dispatches a verifier per finding, so the intermediate output never reaches your main conversation. Only the top-level subagent’s summary returns to you. A nested subagent is configured the same way as a top-level one and resolves from the same scopes. The subagent panel below the prompt input shows the full tree: each row displays a `(+N)` count of descendants, and as of v2.1.193, opening a row shows that subagent’s siblings and direct children with a path back to `main`. The Running tab in `/agents` lists running subagents as a flat list. Depth is counted as the number of subagent levels below the main conversation, regardless of whether each level runs in the foreground or background. A subagent at depth five doesn’t receive the Agent tool and can’t spawn further. The limit is fixed and not configurable. As of Claude Code v2.1.187, a background subagent’s depth is fixed when it is first spawned, and resuming it later doesn’t change that depth. For example, if your main conversation spawns subagent A, and A spawns a background subagent B at depth two, B is still at depth two when you resume it directly from the main conversation. Resuming a subagent from a shallower context doesn’t let it spawn additional levels that the depth limit already prevented. To prevent a specific subagent from spawning others, omit `Agent` from its `tools` list or add it to `disallowedTools`. A fork still can’t spawn another fork. It can spawn other subagent types, and those count toward the depth limit.
+As of Claude Code v2.1.172, a subagent can spawn its own subagents. Use this when a delegated task itself splits into parallel subtasks, such as a reviewer subagent that dispatches a verifier per finding, so the intermediate output never reaches your main conversation. Only the top-level subagent’s summary returns to you. A nested subagent is configured the same way as a top-level one and resolves from the same scopes. The subagent panel below the prompt input shows the full tree: each row displays a `(+N)` count of descendants, and as of v2.1.193, opening a row shows that subagent’s siblings and direct children with a path back to `main`. Depth is counted as the number of subagent levels below the main conversation, regardless of whether each level runs in the foreground or background. A subagent at depth five doesn’t receive the Agent tool and can’t spawn further. The limit is fixed and not configurable. As of Claude Code v2.1.187, a background subagent’s depth is fixed when it is first spawned, and resuming it later doesn’t change that depth. For example, if your main conversation spawns subagent A, and A spawns a background subagent B at depth two, B is still at depth two when you resume it directly from the main conversation. Resuming a subagent from a shallower context doesn’t let it spawn additional levels that the depth limit already prevented. To prevent a specific subagent from spawning others, omit `Agent` from its `tools` list or add it to `disallowedTools`. A fork still can’t spawn another fork. It can spawn other subagent types, and those count toward the depth limit.
###
@@ -796,7 +782,7 @@
Resume subagents
-Each subagent invocation creates a new instance with fresh context. To continue an existing subagent’s work instead of starting over, ask Claude to resume it. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, Claude receives its agent ID. The built-in Explore and Plan agents are one-shot and return no agent ID, so they can’t be resumed; use `general-purpose` or a custom subagent when you need to continue the work. Claude uses the `SendMessage` tool with the agent’s ID as the `to` field to resume it. The `SendMessage` tool is always available for resuming subagents by agent ID or name. Structured team-protocol messages such as `shutdown_request` and `plan_approval_response` require [agent teams](</docs/en/agent-teams>) to be enabled. To resume a subagent, ask Claude to continue the previous work:
+Each subagent invocation creates a new instance with fresh context. To continue an existing subagent’s work instead of starting over, ask Claude to resume it. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, Claude receives its agent ID. The built-in Explore and Plan agents are one-shot and return no agent ID, so they can’t be resumed; use `general-purpose` or a custom subagent when you need to continue the work. Claude uses the `SendMessage` tool with the agent’s ID or name as the `to` field to resume it. `SendMessage` doesn’t require [agent teams](</docs/en/agent-teams>) to be enabled; only structured team-protocol messages such as `shutdown_request` and `plan_approval_response` do. To resume a subagent, ask Claude to continue the previous work:
Use the code-reviewer subagent to review the authentication module
[Agent completes]
@@ -804,7 +790,7 @@
Continue that code review and now analyze the authorization logic
[Claude resumes the subagent with full context from previous conversation]
-If a stopped subagent receives a `SendMessage`, it auto-resumes in the background without requiring a new `Agent` invocation. You can also ask Claude for the agent ID if you want to reference it explicitly, or find IDs in the transcript files at `~/.claude/projects/{project}/{sessionId}/subagents/`. Each transcript is stored as `agent-{agentId}.jsonl`. Subagent transcripts persist independently of the main conversation:
+If a stopped subagent receives a `SendMessage`, it auto-resumes in the background without requiring a new `Agent` invocation. As of v2.1.199, `SendMessage` checks that a name still refers to the same agent it reached earlier in the conversation. If a newer agent has taken the name, such as a re-spawned background agent that reused it, Claude Code refuses the send rather than delivering it to the wrong agent, and the error reports which agent the name now reaches so Claude can retarget. To reach the earlier agent while it’s still running, Claude addresses it by the agent ID from its spawn result. The check is scoped to the current conversation and resets on `/clear`. As of v2.1.198, a subagent treats messages from the agent that launched it as normal task direction, including mid-task course corrections, and acts on them within its own permission settings. Two limits still hold regardless of who sent the message: no message from any agent counts as your approval for a pending permission prompt, and no agent message can change a subagent’s permission settings, `CLAUDE.md`, or configuration. Only the permission system or your own messages can grant approval. You can also ask Claude for the agent ID if you want to reference it explicitly, or find IDs in the transcript files at `~/.claude/projects/{project}/{sessionId}/subagents/`. Each transcript is stored as `agent-{agentId}.jsonl`. 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.
* **Session persistence** : subagent transcripts persist within their session. You can resume a subagent after restarting Claude Code by resuming the same session.
@@ -863,6 +849,8 @@
`x`| Dismiss a finished fork or stop a running one
`Esc`| Return focus to the prompt input
+With a fork’s or subagent’s transcript open, follow-up messages and [skills](</docs/en/skills>) go to that agent, but built-in commands still run in your main conversation. As of v2.1.199, typing `/model` or `/fast` in that view shows a notice that it changes the main conversation’s model or fast mode, not the viewed agent’s, instead of running it silently.
+
###
@@ -910,7 +898,7 @@
Code reviewer
-A read-only subagent that reviews code without modifying it. This example shows how to design a focused subagent with limited tool access (no Edit or Write) and a detailed prompt that specifies exactly what to look for and how to format output.
+A read-only subagent that reviews code without modifying it. This example shows how to design a focused subagent with limited tool access that excludes Edit and Write, and a detailed prompt that specifies exactly what to look for and how to format output.
---
name: code-reviewer
Show diff (197 lines)
--- a/subagents.md
+++ b/subagents.md
@@ -1,4 +1,4 @@
-Subagents are separate agent instances that your main agent can spawn to handle focused subtasks. Use subagents to isolate context for focused subtasks, run multiple analyses in parallel, and apply specialized instructions without adding to the main agent’s prompt. This guide explains how to define and use subagents in the SDK using the `agents` parameter.
+Subagents are separate agent instances that your main agent can spawn to handle focused subtasks. Use them to isolate context, run multiple analyses in parallel, and apply specialized instructions without adding to the main agent’s prompt. This guide explains how to define and use subagents in the SDK using the `agents` parameter.
##
@@ -8,11 +8,11 @@
You can create subagents in three ways:
- * **Programmatically** : use the `agents` parameter in your `query()` options ([TypeScript](</docs/en/agent-sdk/typescript#agentdefinition>), [Python](</docs/en/agent-sdk/python#agentdefinition>))
- * **Filesystem-based** : define agents as markdown files in `.claude/agents/` directories (see [defining subagents as files](</docs/en/sub-agents>))
+ * **Programmatically** : use the `agents` parameter in your `query()` options. See the [TypeScript](</docs/en/agent-sdk/typescript#agentdefinition>) and [Python](</docs/en/agent-sdk/python#agentdefinition>) references
+ * **Filesystem-based** : define agents as markdown files in `.claude/agents/` directories. See [defining subagents as files](</docs/en/sub-agents>)
* **Built-in general-purpose** : Claude can invoke the built-in `general-purpose` subagent at any time via the Agent tool without you defining anything
-This guide focuses on the programmatic approach, which is recommended for SDK applications. When you define subagents, Claude determines whether to invoke them based on each subagent’s `description` field. Write clear descriptions that explain when the subagent should be used, and Claude will automatically delegate appropriate tasks. You can also explicitly request a subagent by name in your prompt (for example, “Use the code-reviewer agent to…”).
+This guide focuses on the programmatic approach, which is recommended for SDK applications. When you define subagents, Claude determines whether to invoke them based on each subagent’s `description` field. Write clear descriptions that explain when to use the subagent, and Claude automatically delegates appropriate tasks. You can also explicitly request a subagent by name in your prompt, for example “Use the code-reviewer agent to…”.
##
@@ -56,7 +56,7 @@
-Creating subagents
+Create subagents
###
@@ -64,7 +64,7 @@
Programmatic definition (recommended)
-Define subagents directly in your code using the `agents` parameter. This example creates two subagents: a code reviewer with read-only access and a test runner that can execute commands. Claude invokes subagents through the `Agent` tool, so include `Agent` in `allowedTools` to auto-approve subagent invocations without a permission prompt. Most examples on this page print only the final result. To confirm that Claude delegated to a subagent rather than answering directly, see Detecting subagent invocation.
+Define subagents directly in your code using the `agents` parameter. Claude invokes subagents through the `Agent` tool, so include `Agent` in `allowedTools` to auto-approve subagent invocations without a permission prompt. Most examples on this page print only the final result. To confirm that Claude delegated to a subagent rather than answering directly, see Detect subagent invocation. This example creates two subagents: a code reviewer with read-only access and a test runner that can execute commands.
Python
@@ -140,9 +140,12 @@
`effort`| `'low' | 'medium' | 'high' | 'xhigh' | 'max' | number`| No| Reasoning effort level for this agent
`permissionMode`| `PermissionMode`| No| Permission mode for tool execution within this agent
-In the Python SDK, multi-word field names such as `disallowedTools` and `mcpServers` keep their camelCase spelling to match the wire format rather than following Python’s snake_case convention. See the [`AgentDefinition` reference](</docs/en/agent-sdk/python#agentdefinition>) for details.
-
-As of Claude Code v2.1.172, subagents can spawn their own subagents. A subagent five levels below the main agent cannot spawn further subagents, regardless of whether it runs in the foreground or background. To prevent a subagent from spawning others, omit `Agent` from its `tools` array or add it to `disallowedTools`. See [nested subagents](</docs/en/sub-agents#spawn-nested-subagents>) for the full depth rules.
+In the Python SDK, multi-word field names such as `disallowedTools` and `mcpServers` keep their camelCase spelling to match the wire format rather than following Python’s snake_case convention. See the [`AgentDefinition` reference](</docs/en/agent-sdk/python#agentdefinition>) for details. Two subagent behaviors changed in Claude Code v2.1.198:
+
+ * Subagents run in the background by default. An Agent tool call that omits the [`run_in_background`](</docs/en/agent-sdk/typescript>) input launches a background subagent, and Claude sets `run_in_background: false` when it needs the result before continuing. Before v2.1.198, omitting `run_in_background` ran the subagent synchronously. Set the `background` field to `true` to force background execution for a specific agent regardless of what Claude requests.
+ * A subagent inherits the main session’s extended thinking configuration. On earlier versions, extended thinking is disabled inside subagents regardless of the main session’s setting.
+
+As of Claude Code v2.1.172, subagents can spawn their own subagents. A subagent five levels below the main agent can’t spawn further subagents, regardless of whether it runs in the foreground or background. To prevent a subagent from spawning others, omit `Agent` from its `tools` array or add it to `disallowedTools`. See [nested subagents](</docs/en/sub-agents#spawn-nested-subagents>) for the full depth rules.
###
@@ -160,21 +163,23 @@
What subagents inherit
-A subagent’s context window starts fresh (no parent conversation) but isn’t empty. The only channel from parent to subagent is the Agent tool’s prompt string, so include any file paths, error messages, or decisions the subagent needs directly in that prompt.
-
-The subagent receives| The subagent does not receive
+A subagent’s context window starts fresh, with no parent conversation, but isn’t empty. The only channel from parent to subagent is the Agent tool’s prompt string, so include any file paths, error messages, or decisions the subagent needs directly in that prompt.
+
+The subagent receives| The subagent doesn’t receive
---|---
Its own system prompt (`AgentDefinition.prompt`) and the Agent tool’s prompt| The parent’s conversation history or tool results
Project CLAUDE.md (loaded via [`settingSources`](</docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources>))| Preloaded skill content, unless listed in `AgentDefinition.skills`
Tool definitions (inherited from parent, or the subset in `tools`)| The parent’s system prompt
-The parent receives the subagent’s final message verbatim as the Agent tool result, but may summarize it in its own response. To preserve subagent output verbatim in the user-facing response, include an instruction to do so in the prompt or `systemPrompt` option you pass to the **main** `query()` call.
-
-##
-
-
-
-Invoking subagents
+The parent receives the subagent’s final message verbatim as the Agent tool result, but may summarize it in its own response. To preserve subagent output verbatim in the user-facing response, include an instruction to do so in the prompt or `systemPrompt` option you pass to the main `query()` call.
+
+As of Claude Code v2.1.199, an API error that ends the subagent early, such as a rate limit, is never delivered as its result. If the subagent already produced output, the Agent tool returns that partial output with a note that the subagent didn’t finish; otherwise the tool result is an error message, `Agent terminated early due to an API error`, followed by the error detail. See [API errors in subagents](</docs/en/sub-agents#api-errors-in-subagents>) for the foreground and background behavior.
+
+##
+
+
+
+Invoke subagents
###
@@ -245,13 +250,13 @@
-Detecting subagent invocation
-
-Subagents are invoked via the Agent tool. To detect when a subagent is invoked, check for `tool_use` blocks where `name` is `"Agent"`. Messages from within a subagent’s context include a `parent_tool_use_id` field.
+Detect subagent invocation
+
+Claude invokes subagents through the Agent tool. To detect when a subagent is invoked, check for `tool_use` blocks where `name` is `"Agent"`. Messages from within a subagent’s context include a `parent_tool_use_id` field.
The tool name was renamed from `"Task"` to `"Agent"` in Claude Code v2.1.63. Current SDK releases emit `"Agent"` in `tool_use` blocks but still use `"Task"` in the `system:init` tools list and in `result.permission_denials[].tool_name`. Checking both values in `block.name` ensures compatibility across SDK versions.
-The message structure differs between SDKs. In Python, content blocks are accessed directly via `message.content`. In TypeScript, `SDKAssistantMessage` wraps the Claude API message, so content is accessed via `message.message.content`. This example iterates through streamed messages, logging when a subagent is invoked and when subsequent messages originate from within that subagent’s execution context.
+The message structure differs between SDKs. In Python, you access content blocks directly via `message.content`. In TypeScript, `SDKAssistantMessage` wraps the Claude API message, so you access content via `message.message.content`. This example iterates through streamed messages, logging when a subagent is invoked and when subsequent messages originate from within that subagent’s execution context.
Python
@@ -297,13 +302,13 @@
-Resuming subagents
-
-Subagents can be resumed to continue where they left off. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, the Agent tool result includes a text block containing `agentId: <id>`. The built-in [`Explore` and `Plan` agents](</docs/en/sub-agents#built-in-subagents>) are one-shot and do not return an `agentId`, so use a custom agent or `general-purpose` when you need to resume. To resume a subagent programmatically:
-
- 1. **Capture the session ID** : Extract `session_id` from messages during the first query
- 2. **Extract the agent ID** : Parse `agentId` from the Agent tool result text
- 3. **Resume the session** : Pass `resume: sessionId` in the second query’s options, and include the agent ID in your prompt
+Resume subagents
+
+You can resume a subagent to continue where it left off rather than starting fresh. A resumed subagent retains its full conversation history, including all previous tool calls, results, and reasoning. When a subagent completes, the Agent tool result includes a text block containing `agentId: <id>`. The built-in [`Explore` and `Plan` agents](</docs/en/sub-agents#built-in-subagents>) are one-shot and don’t return an `agentId`, so use a custom agent or `general-purpose` when you need to resume. To resume a subagent programmatically:
+
+ 1. **Capture the session ID** : extract `session_id` from messages during the first query
+ 2. **Extract the agent ID** : parse `agentId` from the Agent tool result text
+ 3. **Resume the session** : pass `resume: sessionId` in the second query’s options, and include the agent ID in your prompt
You must resume the same session to access the subagent’s transcript. Each `query()` call starts a new session by default, so pass `resume: sessionId` to continue in the same session.When using a custom agent, pass the same agent definition in the `agents` parameter for both queries.
@@ -375,9 +380,9 @@
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.
- * **Session persistence** : Subagent transcripts persist within their session. You can resume a subagent after restarting Claude Code by resuming the same session.
- * **Automatic cleanup** : Transcripts are cleaned up based on the `cleanupPeriodDays` setting (default: 30 days).
+ * **Main conversation compaction** : when the main conversation compacts, subagent transcripts are unaffected. They’re stored in separate files.
+ * **Session persistence** : subagent transcripts persist within their session. You can resume a subagent after restarting Claude Code by resuming the same session.
+ * **Automatic cleanup** : transcripts are cleaned up based on the `cleanupPeriodDays` setting, which defaults to 30 days.
##
@@ -390,7 +395,7 @@
* **Omit the field** : agent inherits all available tools (default)
* **Specify tools** : agent can only use listed tools
-This example creates a read-only analysis agent that can examine code but cannot modify files or run commands.
+This example creates a read-only analysis agent that can examine code but can’t modify files or run commands.
Python
@@ -455,9 +460,9 @@
If Claude completes tasks directly instead of delegating to your subagent:
- 1. **Check Agent invocations are approved** : include `Agent` in `allowedTools` to auto-approve subagent calls. Without it, Agent invocations fall through to your `canUseTool` callback or, in `dontAsk` mode, are denied
- 2. **Use explicit prompting** : mention the subagent by name in your prompt (for example, “Use the code-reviewer agent to…”)
- 3. **Write a clear description** : explain exactly when the subagent should be used so Claude can match tasks appropriately
+ * **Check Agent invocations are approved** : include `Agent` in `allowedTools` to auto-approve subagent calls. Without it, Agent invocations fall through to your `canUseTool` callback or, in `dontAsk` mode, are denied
+ * **Use explicit prompting** : mention the subagent by name in your prompt, for example “Use the code-reviewer agent to…”
+ * **Write a clear description** : explain exactly when to use the subagent so Claude can match tasks appropriately
###
@@ -465,15 +470,22 @@
Filesystem-based agents not loading
-Agents defined in `.claude/agents/` are loaded at startup only. If you create a new agent file while Claude Code is running, restart the session to load it.
-
-###
-
-
-
-Windows: long prompt failures
-
-On Windows, subagents with very long prompts may fail due to command line length limits (8191 chars). Keep prompts concise or use filesystem-based agents for complex instructions.
+Claude Code watches `~/.claude/agents/` and `.claude/agents/` and picks up a new or edited agent file within a few seconds, with no restart needed. If a definition never appears, work through these causes:
+
+ * **New`agents` directory**: the watcher covers only directories that existed when the session started, so the first file in a new directory needs a session restart. This is the most common cause.
+ * **Invalid frontmatter or a duplicate`name`**: check the file’s YAML, and whether an existing agent already uses the `name`.
+ * **`--disable-slash-commands`** : sessions started with this flag don’t watch these directories and always need a restart to load new files.
+ * **A programmatic agent with the same name** : `agents` passed to `query()` override a filesystem agent with the same name.
+
+For the file format, see [how to write subagent files](</docs/en/sub-agents#write-subagent-files>).
+
+###
+
+
+
+Long prompt failures on Windows
+
+On Windows, subagents with very long prompts may fail due to the command line length limit of 8191 characters. Keep prompts concise or use filesystem-based agents for complex instructions.
##
--- a/third-party-integrations.md
+++ b/third-party-integrations.md
@@ -21,7 +21,7 @@
* [Claude for Teams or Enterprise](</docs/en/authentication#claude-for-teams-or-enterprise>)
* [Anthropic Console](</docs/en/authentication#claude-console-authentication>)
- * [Claude apps gateway](</docs/en/claude-apps-gateway>), a self-hosted gateway that adds IdP sign-in in front of Amazon Bedrock, Google Vertex AI, Microsoft Foundry, or the Anthropic API
+ * [Claude apps gateway](</docs/en/claude-apps-gateway>), a self-hosted gateway that adds IdP sign-in in front of Amazon Bedrock, Claude Platform on AWS, Google Vertex AI, Microsoft Foundry, or the Anthropic API
* [Amazon Bedrock](</docs/en/amazon-bedrock>)
* [Claude Platform on AWS](</docs/en/claude-platform-on-aws>)
* [Google Vertex AI](</docs/en/google-vertex-ai>)
--- a/todo-tracking.md
+++ b/todo-tracking.md
@@ -33,6 +33,8 @@
Examples
+
+Before running these examples, install the Claude Agent SDK by following the [quickstart](</docs/en/agent-sdk/quickstart>).
###
Show diff (147 lines)
--- a/tools-reference.md
+++ b/tools-reference.md
@@ -1,10 +1,10 @@
Claude Code has access to a set of built-in tools that help it understand and modify your codebase. The tool names are the exact strings you use in [permission rules](</docs/en/permissions#tool-specific-permission-rules>), [subagent tool lists](</docs/en/sub-agents>), and [hook matchers](</docs/en/hooks>). To disable a tool entirely, add its name to the `deny` array in your [permission settings](</docs/en/permissions#tool-specific-permission-rules>). To add custom tools, connect an [MCP server](</docs/en/mcp>). To extend Claude with reusable prompt-based workflows, write a [skill](</docs/en/skills>), which runs through the existing `Skill` tool rather than adding a new tool entry.
-Tool| Description| Permission Required
+Tool| Description| Permission required
---|---|---
`Agent`| Spawns a [subagent](</docs/en/sub-agents>) with its own context window to handle a task. See Agent tool behavior| No
-`Artifact`| Publishes an HTML or Markdown file as an [artifact](</docs/en/artifacts>): a private, interactive page on claude.ai you can share inside your organization. Requires a Team or Enterprise plan and `/login` authentication; see [Availability](</docs/en/artifacts#availability>)| Yes
-`AskUserQuestion`| Asks multiple-choice questions to gather requirements or clarify ambiguity| No
+`Artifact`| Publishes an HTML or Markdown file as an [artifact](</docs/en/artifacts>): a private, interactive page on claude.ai. On Team and Enterprise plans, you can share it inside your organization. Requires a Pro, Max, Team, or Enterprise plan and `/login` authentication; see [Availability](</docs/en/artifacts#availability>)| Yes
+`AskUserQuestion`| Asks multiple-choice questions to gather requirements or clarify ambiguity. As of v2.1.198, if you don’t respond within 60 seconds the dialog closes on its own: it submits any options you’d already selected and tells Claude you may be away from your keyboard, so Claude proceeds on its own judgment and can re-ask later. A countdown appears for the last 20 seconds. Any keypress keeps the dialog open, and so does a focused window on terminals that report focus. Set the [`CLAUDE_AFK_TIMEOUT_MS`](</docs/en/env-vars#variables>) environment variable to change how long Claude Code waits, or to a large value like `86400000`, 24 hours, to keep questions open while you’re away. This timeout applies only to `AskUserQuestion`’s multiple-choice questions; permission prompts, including plan approval, never auto-resolve on idle| No
`Bash`| Executes shell commands in your environment. See Bash tool behavior| Yes
`CronCreate`| Schedules a recurring or one-shot prompt within the current session. Tasks are session-scoped and restored on `--resume` or `--continue` if unexpired. See [scheduled tasks](</docs/en/scheduled-tasks>)| No
`CronDelete`| Cancels a scheduled task by ID| No
@@ -25,9 +25,9 @@
`Read`| Reads the contents of files. See Read tool behavior| No
`ReadMcpResourceTool`| Reads a specific MCP resource by URI| No
`RemoteTrigger`| Creates, updates, runs, and lists [Routines](</docs/en/routines>) on claude.ai. Backs the `/schedule` command. Routines live on claude.ai and require a Pro, Max, Team, or Enterprise plan, so this tool is not accessible from Amazon Bedrock, Google Vertex AI, or Microsoft Foundry| No
-`ReportFindings`| Reports code-review findings as a structured list, with a file, summary, and failure scenario per finding, so Claude Code can render them instead of printing them as text. Claude calls it when active code-review instructions tell it to. Requires Claude Code v2.1.196 or later| No
+`ReportFindings`| Reports code-review findings as a structured list, with a file, summary, and failure scenario per finding, so Claude Code can render them instead of printing them as text. Claude calls it when active code-review instructions tell it to. Requires Claude Code v2.1.196 or later. As of v2.1.199, a finding can also carry an optional `category` slug, such as `correctness` or `test-coverage`, shown next to the file location in the rendered list| No
`ScheduleWakeup`| Reschedules the next iteration of a [self-paced `/loop`](</docs/en/scheduled-tasks#let-claude-choose-the-interval>). Claude calls this at the end of each iteration to pick when the next one runs, between one minute and one hour out; you don’t call it directly. The pending wakeup appears in `session_crons` in [Stop hook input](</docs/en/hooks#stop-input>). Not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry, where a `/loop` prompt with no interval runs on a fixed schedule instead| No
-`SendMessage`| Sends a message to an [agent team](</docs/en/agent-teams>) teammate, or [resumes a subagent](</docs/en/sub-agents#resume-subagents>) by its agent ID. Stopped subagents auto-resume in the background. Structured team-protocol messages require agent teams| No
+`SendMessage`| Sends a message to an [agent team](</docs/en/agent-teams>) teammate, or [resumes a subagent](</docs/en/sub-agents#resume-subagents>) by its agent ID or name. Stopped subagents auto-resume in the background. Structured team-protocol messages require agent teams. A receiver never treats a message from another agent as your consent or approval. As of v2.1.198, a subagent treats a message from the agent that launched it as normal task direction rather than as a peer request. As of v2.1.199, a send to a name that now resolves to a different agent than it did earlier in the conversation is refused instead of delivered; see [Resume subagents](</docs/en/sub-agents#resume-subagents>)| No
`SendUserFile`| Sends files from the session to you with an optional caption, so a generated report, diagram, screenshot, or built artifact reaches your device instead of only being mentioned in the transcript. As of v2.1.196, the optional `display` input controls presentation: `render` opens the file inline in the client, `attach` shows a download card only, and when unset the client decides by file type. Available when a [Remote Control](</docs/en/remote-control>) client is connected or the session runs in a managed cloud environment such as [Claude Code on the web](</docs/en/claude-code-on-the-web>). Delivery runs through Anthropic-hosted infrastructure, so the tool is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry| No
`ShareOnboardingGuide`| Uploads `ONBOARDING.md` and returns a share link teammates can open in Claude Code. Called from `/team-onboarding` after the guide is written. Available to claude.ai subscribers on Pro, Max, Team, and Enterprise plans| Yes
`Skill`| Executes a [skill](</docs/en/skills#control-who-invokes-a-skill>) within the main conversation| Yes
@@ -35,11 +35,11 @@
`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`| Kills a running background task by ID| 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
`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
-`WaitForMcpServers`| Waits for one or more [MCP servers](</docs/en/mcp>) that are still connecting in the background, so a request can use their tools without restarting the session. Claude calls it when a needed server is not connected yet. Only appears when [tool search](</docs/en/mcp#scale-with-mcp-tool-search>) is disabled, since `ToolSearch` handles the wait when it’s enabled| No
+`WaitForMcpServers`| Waits for one or more [MCP servers](</docs/en/mcp>) that are still connecting in the background, so a request can use their tools without restarting the session. Claude calls it when a needed server isn’t connected yet. Only appears when [tool search](</docs/en/mcp#scale-with-mcp-tool-search>) is disabled, since `ToolSearch` handles the wait when it’s enabled| No
`WebFetch`| Fetches content from a specified URL. See WebFetch tool behavior| Yes
`WebSearch`| Performs web searches. See WebSearch tool behavior| Yes
`Workflow`| Runs a [dynamic workflow](</docs/en/workflows>): a script that orchestrates many subagents in the background and returns one consolidated result| Yes
@@ -81,14 +81,14 @@
Agent tool behavior
-The Agent tool spawns a subagent in a separate context window. The subagent works through its task autonomously, then returns a single text result to the parent conversation. The parent does not see the subagent’s intermediate tool calls or outputs, only that final result. To cap how many turns a subagent runs, set `maxTurns` in the [subagent definition](</docs/en/sub-agents#supported-frontmatter-fields>). The same Agent tool also launches [forked subagents](</docs/en/sub-agents#fork-the-current-conversation>) when fork mode is enabled. A fork inherits the full parent conversation instead of starting fresh, always runs in the background, and still surfaces permission prompts in your terminal. The rest of this section describes named subagents. Which tools a named subagent can use depends on the `tools` and `disallowedTools` fields in the [subagent definition](</docs/en/sub-agents>):
+The Agent tool spawns a subagent in a separate context window. The subagent works through its task autonomously, then returns a single text result to the parent conversation. The parent doesn’t see the subagent’s intermediate tool calls or outputs, only that final result. To cap how many turns a subagent runs, set `maxTurns` in the [subagent definition](</docs/en/sub-agents#supported-frontmatter-fields>). The same Agent tool also launches [forked subagents](</docs/en/sub-agents#fork-the-current-conversation>) when fork mode is enabled. A fork inherits the full parent conversation instead of starting fresh, always runs in the background, and still surfaces permission prompts in your terminal. The rest of this section describes named subagents. Which tools a named subagent can use depends on the `tools` and `disallowedTools` fields in the [subagent definition](</docs/en/sub-agents>):
* **Neither field set** : the subagent inherits every tool available to the parent.
* **`tools` only**: the subagent gets only the listed tools.
* **`disallowedTools` only**: the subagent gets every parent tool except the listed ones.
* **Both set** : `disallowedTools` takes precedence. A tool listed in both is removed.
-Launching the subagent does not itself prompt for permission. The subagent’s own tool calls are checked against your permission rules as it runs:
+Launching the subagent doesn’t itself prompt for permission. Claude Code checks the subagent’s own tool calls against your permission rules as it runs. As of v2.1.198, subagents run in the background by default; Claude runs one in the foreground when it needs the result before continuing.
* **Foreground subagents** show the same permission prompts you would see in the main conversation, at the moment each tool call happens.
* **Background subagents** surface permission prompts in your main session as of v2.1.186. The prompt names which subagent is asking, and pressing Esc denies that one tool call without stopping the subagent. Before v2.1.186, background subagents auto-denied any tool call that would otherwise prompt and continued without that tool.
@@ -122,7 +122,7 @@
Edit tool behavior
-The Edit tool performs exact string replacement. It takes an `old_string` and a `new_string` and replaces the first with the second. It does not use regex or fuzzy matching. Three checks must pass for an edit to apply:
+The Edit tool performs exact string replacement. It takes an `old_string` and a `new_string` and replaces the first with the second. It doesn’t use regex or fuzzy matching. Three checks must pass for an edit to apply:
* **Read-before-edit** : Claude must have read the file in the current conversation, and the file must not have changed on disk since that read. This check runs first, before any string matching.
* **Match** : `old_string` must appear in the file exactly as written. A single character of whitespace or indentation difference is enough to miss.
@@ -142,7 +142,7 @@
* `src/**/*.ts` matches all `.ts` files under `src/`
* `*.{json,yaml}` matches `.json` and `.yaml` files in the current directory
-Results are sorted by modification time and capped at 100 files. If the cap is hit, Claude sees a truncation flag in the result and can narrow the pattern. Glob does not respect `.gitignore` by default, so it finds gitignored files alongside tracked ones. This differs from Grep, which skips gitignored files. To make Glob respect `.gitignore`, set `CLAUDE_CODE_GLOB_NO_IGNORE=false` before launching Claude Code.
+Results are sorted by modification time and capped at 100 files. If the cap is hit, Claude sees a truncation flag in the result and can narrow the pattern. Glob doesn’t respect `.gitignore` by default, so it finds gitignored files alongside tracked ones. This differs from Grep, which skips gitignored files. To make Glob respect `.gitignore`, set `CLAUDE_CODE_GLOB_NO_IGNORE=false` before launching Claude Code.
##
@@ -224,7 +224,7 @@
NotebookEdit tool behavior
-NotebookEdit modifies a Jupyter notebook one cell at a time, targeting cells by their `cell_id`. It does not perform string replacement across the notebook the way Edit does on plain files. Three edit modes control what happens to the target cell:
+NotebookEdit modifies a Jupyter notebook one cell at a time, targeting cells by their `cell_id`. It doesn’t perform string replacement across the notebook the way Edit does on plain files. Three edit modes control what happens to the target cell:
* `replace`: overwrite the cell’s source. This is the default.
* `insert`: add a new cell after the target. With no `cell_id`, the new cell goes at the start of the notebook. Requires `cell_type` set to `code` or `markdown`.
@@ -238,7 +238,11 @@
PowerShell tool
-The PowerShell tool lets Claude run PowerShell commands natively. On Windows, this means commands run in PowerShell instead of routing through Git Bash. On Windows without Git Bash, the tool is enabled automatically. On Windows with Git Bash installed, the tool is rolling out progressively. On Linux, macOS, and WSL, the tool is opt-in.
+The PowerShell tool lets Claude run PowerShell commands natively. On Windows, this means commands run in PowerShell instead of routing through Git Bash. How the tool becomes available depends on your platform:
+
+ * **Windows without Git Bash** : the tool is enabled automatically.
+ * **Windows with Git Bash installed** : the tool is rolling out progressively.
+ * **Linux, macOS, and WSL** : the tool is opt-in.
###
@@ -254,7 +258,7 @@
}
}
-On Windows, set the variable to `0` to opt out of the rollout. On Linux, macOS, and WSL, the tool requires PowerShell 7 or later: install `pwsh` and ensure it is on your `PATH`. On Windows, Claude Code auto-detects `pwsh.exe` for PowerShell 7+ with a fallback to `powershell.exe` for PowerShell 5.1. When the tool is enabled, Claude treats PowerShell as the primary shell. The Bash tool remains available for POSIX scripts when Git Bash is installed. Claude Code spawns PowerShell with `-ExecutionPolicy Bypass` at process scope only, so `.ps1` scripts and module imports work on default Windows installs without changing the machine’s policy. Process-scope bypass does not override Group Policy `MachinePolicy` or `UserPolicy`, so enterprise lockdowns still apply. To respect the machine’s effective execution policy instead, set `CLAUDE_CODE_POWERSHELL_RESPECT_EXECUTION_POLICY=1`.
+On Windows, set the variable to `0` to opt out of the rollout. On Linux, macOS, and WSL, the tool requires PowerShell 7 or later: install `pwsh` and ensure it is on your `PATH`. On Windows, Claude Code auto-detects `pwsh.exe` for PowerShell 7+ with a fallback to `powershell.exe` for PowerShell 5.1. When the tool is enabled, Claude treats PowerShell as the primary shell. The Bash tool remains available for POSIX scripts when Git Bash is installed. Claude Code spawns PowerShell with `-ExecutionPolicy Bypass` at process scope only, so `.ps1` scripts and module imports work on default Windows installs without changing the machine’s policy. Process-scope bypass doesn’t override Group Policy `MachinePolicy` or `UserPolicy`, so enterprise policies still apply. To respect the machine’s effective execution policy instead, set `CLAUDE_CODE_POWERSHELL_RESPECT_EXECUTION_POLICY=1`.
###
@@ -301,14 +305,14 @@
WebFetch tool behavior
-WebFetch takes a URL and a prompt describing what to extract. It fetches the page, converts the response to Markdown when the server returns HTML, and runs the prompt against the content using a small, fast model. For most fetches, Claude receives that model’s answer, not the raw page. The conversion step is not configurable. This makes WebFetch lossy by design. The extraction prompt determines what reaches Claude, so a result that says a page does not mention something may only mean the prompt did not ask about it. Ask Claude to fetch again with a more specific prompt, or use `curl` via Bash for the unprocessed page. A few behaviors shape the response Claude receives:
+WebFetch takes a URL and a prompt describing what to extract. It fetches the page, converts the response to Markdown when the server returns HTML, and runs the prompt against the content using a small, fast model. For most fetches, Claude receives that model’s answer, not the raw page. The conversion step is not configurable. This makes WebFetch lossy by design. The extraction prompt determines what reaches Claude, so a result that says a page doesn’t mention something may only mean the prompt didn’t ask about it. Ask Claude to fetch again with a more specific prompt, or use `curl` via Bash for the unprocessed page. A few behaviors shape the response Claude receives:
* HTTP URLs are automatically upgraded to HTTPS.
* Large pages are truncated to a fixed character limit before processing.
* Responses are cached for 15 minutes, so repeated fetches of the same URL return quickly.
* When a URL redirects to a different host, WebFetch returns a text result that names the original URL and the redirect target instead of following it. Claude then fetches the new URL with a second WebFetch call.
-In the default and `acceptEdits` permission modes, WebFetch prompts the first time it reaches a new domain, except for a built-in set of preapproved documentation domains that fetch without a prompt. To allow another domain in advance without a prompt, add a permission rule like `WebFetch(domain:example.com)`. The `auto` and `bypassPermissions` [permission modes](</docs/en/permissions#permission-modes>) skip the prompt entirely. An explicit `WebFetch(domain:...)` rule in `deny`, `ask`, or `allow` takes precedence over the preapproved set, so you can block a preapproved domain or require a prompt for it. WebFetch sets a `User-Agent` header beginning with `Claude-User`, and an `Accept` header that prefers Markdown over HTML so servers that support content negotiation can return Markdown directly. [Sandbox](</docs/en/sandboxing>) network rules are configured separately, so a domain you want a sandboxed process to reach still needs an explicit sandbox permission rule.
+In the default and `acceptEdits` permission modes, WebFetch prompts the first time it reaches a new domain, except for a built-in set of preapproved documentation domains that fetch without a prompt. To allow another domain in advance without a prompt, add a permission rule like `WebFetch(domain:example.com)`. The `auto` and `bypassPermissions` [permission modes](</docs/en/permissions#permission-modes>) skip the prompt entirely. An explicit `WebFetch(domain:...)` rule in `deny`, `ask`, or `allow` takes precedence over the preapproved set, so you can block a preapproved domain or require a prompt for it. WebFetch sets a `User-Agent` header beginning with `Claude-User`, and an `Accept` header that prefers Markdown over HTML so servers that support content negotiation can return Markdown directly. You configure [sandbox](</docs/en/sandboxing>) network rules separately, so a domain you want a sandboxed process to reach still needs an explicit sandbox permission rule.
##
@@ -316,9 +320,9 @@
WebSearch tool behavior
-WebSearch runs a query against Anthropic’s [web search](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool>) backend and returns result titles and URLs. It does not fetch the result pages. To read a page Claude finds in search results, it follows up with WebFetch. The tool may issue up to eight backend searches per call, refining the search internally before returning results. Claude can scope results with `allowed_domains` to include only certain hosts, or `blocked_domains` to exclude them. The two lists can’t be combined in a single call. The search backend is not configurable. To search with a different provider, add an [MCP server](</docs/en/mcp>) that exposes a search tool. WebSearch permission rules take no specifier. A bare `WebSearch` entry in `allow` or `deny` is the only form.
-
-WebSearch is available on the Claude API and Microsoft Foundry. On Google Cloud Vertex AI it works with Claude 4 and later models, including Opus, Sonnet, and Haiku. Amazon Bedrock does not expose the server-side web search tool.
+WebSearch runs a query against Anthropic’s [web search](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool>) backend and returns result titles and URLs. It doesn’t fetch the result pages. To read a page Claude finds in search results, it follows up with WebFetch. The tool may issue up to eight backend searches per call, refining the search internally before returning results. Claude can scope results with `allowed_domains` to include only certain hosts, or `blocked_domains` to exclude them. The two lists can’t be combined in a single call. The search backend is not configurable. To search with a different provider, add an [MCP server](</docs/en/mcp>) that exposes a search tool. WebSearch permission rules take no specifier. A bare `WebSearch` entry in `allow` or `deny` is the only form.
+
+WebSearch is available on the Claude API, [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), and Microsoft Foundry. On Google Cloud Vertex AI it works with Claude 4 and later models, including Opus, Sonnet, and Haiku. Amazon Bedrock doesn’t expose the server-side web search tool.
##
@@ -326,7 +330,7 @@
Write tool behavior
-The Write tool creates a new file or overwrites an existing one with the full content provided. It does not append or merge. If the target path already exists, Claude must have read that file at least once in the current conversation before overwriting it. A Write to an unread existing file fails with an error. This constraint does not apply to new files. Viewing the file with Bash also satisfies this requirement under the same rules described in Edit tool behavior. For partial changes to an existing file, Claude uses Edit instead of Write.
+The Write tool creates a new file or overwrites an existing one with the full content provided. It doesn’t append or merge. If the target path already exists, Claude must have read that file at least once in the current conversation before overwriting it. A Write to an unread existing file fails with an error. This constraint doesn’t apply to new files. Viewing the file with Bash also satisfies this requirement under the same rules described in Edit tool behavior. For partial changes to an existing file, Claude uses Edit instead of Write.
##
--- a/typescript.md
+++ b/typescript.md
@@ -567,7 +567,7 @@
});
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
- * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1` to retry capacity errors indefinitely.
+ * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
@@ -902,8 +902,9 @@
decisionReason?: string;
toolUseID: string;
agentID?: string;
+ requestId: string;
}
- ) => Promise<PermissionResult>;
+ ) => Promise<PermissionResult | null>;
Option| Type| Description
---|---|---
@@ -913,6 +914,9 @@
`decisionReason`| `string`| Explains why this permission request was triggered
`toolUseID`| `string`| Unique identifier for this specific tool call within the assistant message
`agentID`| `string`| If running within a sub-agent, the sub-agent’s ID
+`requestId`| `string`| The `control_request` envelope’s `request_id`. A `control_response` your application sends outside the SDK, such as a signed HTTP POST, must echo this value so the Claude Code process can match the reply to the request
+
+The callback normally resolves the request by returning a `PermissionResult`, which the SDK writes back over its transport as the `control_response`. Return `null` only when your application has already sent the `control_response` for this request over its own channel, echoing `requestId`; the SDK then skips writing the response to its transport. Returning `null` in any other case leaves the tool call blocked indefinitely, because no `control_response` is ever sent and permission prompts don’t time out. The `requestId` option and the `null` return value require Claude Code v2.1.199 or later.
###
@@ -2175,7 +2179,7 @@
shell_id?: string; // Deprecated: use task_id
};
-Stops a running background task or shell by ID.
+Stops a running background task or shell by ID. As of v2.1.198, `task_id` also accepts an agent-team teammate or a named background agent by agent ID or name.
###
@@ -3779,7 +3783,7 @@
`enableWeakerNestedSandbox`| `boolean`| `false`| Enable a weaker nested sandbox for compatibility
`ripgrep`| `{ command: string; args?: string[] }`| `undefined`| Custom ripgrep binary configuration for sandbox environments
-The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. When `enabled` is `true` and the sandbox can’t start, `query()` reports a `result` message with `subtype: "error_during_execution"` and the reason in `errors`, then stops. Watch for that subtype rather than expecting `query()` to throw before yielding messages.To run unsandboxed instead, set `failIfUnavailable: false`.
+The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. When `enabled` is `true` and the sandbox can’t start, `query()` reports a `result` message with `subtype: "error_during_execution"` and the reason in `errors`. For a single message `query()` call, the SDK throws after yielding that error result, so wrap the loop in a try block to continue past it. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the error contract.To run unsandboxed instead, set `failIfUnavailable: false`.
####
@@ -3789,19 +3793,25 @@
import { query } from "@anthropic-ai/claude-agent-sdk";
- for await (const message of query({
- prompt: "Build and test my project",
- options: {
- sandbox: {
- enabled: true,
- autoAllowBashIfSandboxed: true,
- network: {
- allowLocalBinding: true
+ try {
+ for await (const message of query({
+ prompt: "Build and test my project",
+ options: {
+ sandbox: {
+ enabled: true,
+ autoAllowBashIfSandboxed: true,
+ network: {
+ allowLocalBinding: true
+ }
}
}
+ })) {
+ if ("result" in message) console.log(message.result);
}
- })) {
- if ("result" in message) console.log(message.result);
+ } catch (error) {
+ // A single-shot query() throws after yielding an error result,
+ // such as when the sandbox can't start (failIfUnavailable defaults to true).
+ console.log(`Session ended with an error: ${error}`);
}
**Unix socket security:** The `allowUnixSockets` option can grant access to powerful system services. For example, allowing `/var/run/docker.sock` effectively grants full host system access through the Docker API, bypassing sandbox isolation. Only allow Unix sockets that are strictly necessary and understand the security implications of each.
Show diff (102 lines)
--- a/workflows.md
+++ b/workflows.md
@@ -188,6 +188,99 @@
+Example workflow prompts
+
+A workflow fits best when the task is larger than one agent can hold in context, or when the same step needs to run across many items. The prompts below show common shapes. Each one asks Claude to write and run a workflow for that task; you don’t write the script yourself.
+
+###
+
+
+
+Audit many files for the same issue
+
+Fan out one agent per file, then collect and verify the findings.
+
+ > use a workflow to audit every route handler under src/routes/ for missing authentication checks, and adversarially verify each finding before reporting it
+
+###
+
+
+
+Keep fixing until a check passes
+
+Run a checker, fix what failed, and repeat until it passes or stops making progress.
+
+ > use a workflow to run npx tsc --noEmit and keep fixing the reported errors until the type check passes or two rounds in a row make no progress
+
+###
+
+
+
+Migrate many files in parallel
+
+Discover the files to migrate, transform each one in an isolated copy so edits don’t conflict, and verify each result.
+
+ > use a workflow to migrate every component under src/components/ from styled-components to Tailwind, working on each file in its own isolated copy
+
+###
+
+
+
+Review every changed file and write one summary
+
+Run a reviewer per file, then hand all the findings to one agent that ranks and deduplicates them.
+
+ > use a workflow to review every file changed in this PR for correctness issues, then merge the per-file findings into one ranked summary
+
+###
+
+
+
+Research a topic across many sources
+
+Fan out readers across changelogs, issues, and docs, then synthesize. The bundled `/deep-research` workflow does this; you can also describe a narrower version.
+
+ > use a workflow to research how our three competitors handle rate limiting: read their public docs and recent changelog entries in parallel, then compare the approaches
+
+###
+
+
+
+Find issues until the list stops growing
+
+Keep searching in rounds and stop when new rounds turn up nothing new.
+
+ > use a workflow to find flaky tests in this repo: run the suite repeatedly, record which tests fail intermittently, and stop once two rounds in a row find nothing new
+
+###
+
+
+
+What the saved script looks like
+
+When you save a workflow, the file in `.claude/workflows/` holds a `meta` block followed by a script body that orchestrates subagents. You usually don’t need to edit it, but here is the shape of a small one so you can recognize what Claude generated:
+
+ export const meta = {
+ name: 'audit-routes',
+ description: 'Audit every route handler for missing auth checks',
+ }
+
+ const found = await agent('List every .ts file under src/routes/.', {
+ schema: { type: 'object', required: ['files'], properties: { files: { type: 'array', items: { type: 'string' } } } },
+ })
+
+ const audits = await pipeline(found.files, file =>
+ agent(`Audit ${file} for missing authentication checks.`, { label: file }),
+ )
+
+ return audits.filter(Boolean)
+
+The body is plain JavaScript with top-level `await`. `agent()` spawns one subagent and `pipeline()` runs one per item in a list. If you want to edit a script by hand, ask Claude to walk you through the change, or see the Workflow tool entry in the [Agent SDK reference](</docs/en/agent-sdk/typescript>) for the full set of options.
+
+##
+
+
+
How a workflow runs
The workflow runtime executes the script in an isolated environment, separate from your conversation. Intermediate results stay in script variables instead of landing in Claude’s context. Every run writes its script to a file under your session’s directory in `~/.claude/projects/`. Claude receives the path when the run starts, so you can ask for it. You can open that file to read the orchestration Claude wrote, diff it against a previous run’s script, or edit it and ask Claude to relaunch from the edited version. The runtime tracks each agent’s result as the run progresses, which is what makes a run resumable within the same session.
--- a/worktrees.md
+++ b/worktrees.md
@@ -18,7 +18,7 @@
claude --worktree
-You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it.
+You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it.
Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout.