modified Set up Claude Code for your organization View current →
--- a/admin-setup.md +++ b/admin-setup.md @@ -34,7 +34,7 @@ Decide how settings reach devices -Managed settings define organization policy. Claude Code checks the four sources in the table below in priority order and applies the first one that delivers at least one policy key. [Which managed source Claude Code uses](</docs/en/managed-settings#precedence-within-the-managed-tier>) covers what still applies from the other sources and what a policy helper changes; the table is the decision map. +Managed settings define organization policy. Claude Code checks the four sources in the table below in priority order. [How Claude Code combines managed sources](</docs/en/managed-settings#precedence-within-the-managed-tier>) says which of them apply, what a policy helper changes, and how to compose every source. The table is the decision map. Mechanism| Delivery| Priority| Platforms ---|---|---|---
modified Escalate hard decisions with the advisor tool View current →
--- a/advisor.md +++ b/advisor.md @@ -130,7 +130,7 @@ When Claude calls the advisor, the transcript shows an `Advising` line with the advisor model name while the call is in progress. When the result returns, the line reports whether the advisor gave guidance: - * **Reviewed** : the line confirms that the advisor has reviewed the conversation. Press `Ctrl+O` to expand it and read the advisor’s full guidance. + * **Reviewed** : the line confirms that the advisor has reviewed the conversation. When the advisor returned readable guidance, press `Ctrl+O` to read it. * **Declined** : the line reads `Advisor declined to advise on this request`. If the advisor gave a reason, press `Ctrl+O` to read it. Claude generally follows the advisor’s guidance, but adapts when its own evidence contradicts a specific claim: if a recommended step fails when tried, or the file contents contradict the advice, Claude surfaces the conflict rather than following the guidance unconditionally. The advisor always receives the full conversation, and Claude controls the timing. For more control or a different configuration, see how the advisor compares with subagents and opusplan.
modified How the agent loop works View current →
--- a/agent-loop.md +++ b/agent-loop.md @@ -190,7 +190,7 @@ Max turns (`max_turns` / `maxTurns`)| Maximum tool-use round trips| No limit Max budget (`max_budget_usd` / `maxBudgetUsd`)| Maximum cost before stopping| No limit -When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See Handle the result for how to check these subtypes and [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) / [`Options`](</docs/en/agent-sdk/typescript#options>) for syntax. The budget cap covers [subagents](</docs/en/agent-sdk/subagents>): their spend counts toward the total. Once spend reaches the cap, spawning another subagent fails with `Budget limit reached`, and Claude Code stops any background subagents still running. The cap-enforcement behaviors require Claude Code v2.1.217 or later. With [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>), a message you send while a turn is still running stays queued when that turn ends at the max-turns limit, and it starts its own turn with its own max-turns limit. +When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See Handle the result for how to check these subtypes and [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) / [`Options`](</docs/en/agent-sdk/typescript#options>) for syntax. The budget cap covers [subagents](</docs/en/agent-sdk/subagents>): their spend counts toward the total. Once spend reaches the cap, spawning another subagent fails with `Budget limit reached`, and Claude Code stops any background subagents still running. The cap-enforcement behaviors require Claude Code v2.1.217 or later. With [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>), a message that is still queued when a turn ends at the max-turns limit stays queued. Claude Code doesn’t add it to that turn’s last model call. It starts a new turn for the message, and the max-turns count starts over for that turn. ###
modified Orchestrate teams of Claude Code sessions View current →
--- a/agent-teams.md +++ b/agent-teams.md @@ -1,6 +1,6 @@ Agent teams are experimental and disabled by default. Enable them by setting `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` in your [settings.json](</docs/en/settings>) or environment. Without that variable, no team is set up at session start, no team directories are written, and Claude does not spawn or propose teammates. Agent teams have known limitations around session resumption, task coordination, and shutdown behavior. -Agent teams let you coordinate multiple Claude Code instances working together. One session acts as the team lead, coordinating work, assigning tasks, and synthesizing results. Teammates work independently, each in its own context window, and communicate directly with each other. Unlike [subagents](</docs/en/sub-agents>), which run within a single session, you can also interact with individual teammates directly without going through the lead. +Agent teams let you coordinate multiple Claude Code instances working together. One session acts as the team lead, coordinating work, assigning tasks, and synthesizing results. Teammates work independently, each in its own context window, and communicate directly with each other. You can also talk to any teammate directly without going through the lead. Before you set up a team, check whether a lighter option does the job. [Subagents](</docs/en/sub-agents>) work within a single session, and with [cross-session messaging](</docs/en/cross-session-messaging>) Claude can pass findings between the sessions you run yourself. This page describes agent teams as of v2.1.178. With `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` set, spawning a teammate no longer needs a setup step, and cleanup happens automatically when the session exits. Before v2.1.178, you asked Claude to create and name a team first, and Claude used the `TeamCreate` and `TeamDelete` tools to set it up and remove it. Both tools no longer exist. The `team_name` input on the Agent tool is accepted but ignored, and the `team_name` field in `TaskCreated`, `TaskCompleted`, and `TeammateIdle` [hook payloads](</docs/en/hooks#taskcreated>) carries the session-derived name and is deprecated. @@ -73,7 +73,7 @@ * **Up and down arrows** : select a teammate * **Enter** : open the selected teammate’s transcript and message it directly - * **Escape** : interrupt the selected teammate’s current turn + * **Escape** : clear the selection. While you’re viewing a teammate’s transcript, Escape interrupts that teammate’s current turn 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. @@ -124,7 +124,12 @@ Spawn 4 teammates to refactor these modules in parallel. Use Sonnet for each teammate. -When your prompt doesn’t name a model for a teammate, Claude Code runs the teammate on the lead’s current model, unless [`CLAUDE_CODE_SUBAGENT_MODEL`](</docs/en/model-config#environment-variables>) is set. +Claude Code picks each teammate’s model from the first of these that applies: + + 1. [`CLAUDE_CODE_SUBAGENT_MODEL`](</docs/en/model-config#environment-variables>), when it’s set to anything other than `inherit`. + 2. The model your spawn prompt names for that teammate. + 3. For an in-process teammate spawned from a subagent definition, the definition’s `model`. + 4. The lead’s current model. `teammateDefaultModel` was removed in v2.1.234; Claude Code ignores a leftover value. Name the model in your prompt or set `CLAUDE_CODE_SUBAGENT_MODEL` instead. @@ -139,14 +144,13 @@ ​ -Require plan approval for teammates - -For complex or risky tasks, you can require teammates to plan before implementing. The teammate works in read-only plan mode until the lead approves their approach: +Have teammates plan before implementing + +For complex or risky tasks, you can have teammates plan before implementing. A teammate that Claude spawns while the lead is in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) works in read-only plan mode until its plan is ready. Switch the lead into plan mode first, then ask for the teammate: Spawn an architect teammate to refactor the authentication module. - Require plan approval before they make any changes. - -When a teammate finishes planning, it sends a plan approval request to the lead. The lead reviews the plan and either approves it or rejects it with feedback. If rejected, the teammate stays in plan mode, revises based on the feedback, and resubmits. Once approved, the teammate exits plan mode and begins implementation. The lead makes approval decisions autonomously. To influence the lead’s judgment, give it criteria in your prompt, such as “only approve plans that include test coverage” or “reject plans that modify the database schema.” + +When a teammate finishes planning, it sends a plan approval request to the lead. Claude Code approves the plan in the lead’s session as soon as the request arrives, without the lead reviewing it. The teammate’s edits and commands still go through the permission prompts described in Permissions. Once approved, the teammate exits plan mode and begins implementation. ### @@ -242,13 +246,17 @@ Use subagent definitions for teammates -When spawning a teammate, you can reference a [subagent](</docs/en/sub-agents>) type from any [subagent scope](</docs/en/sub-agents#choose-the-subagent-scope>): project, user, plugin, or CLI-defined. This lets you define a role once, such as a security-reviewer or test-runner, and reuse it both as a delegated subagent and as an agent team teammate. To use a subagent definition, mention it by name when asking Claude to spawn the teammate: +When spawning a teammate, you can reference a [subagent](</docs/en/sub-agents>) type from any [subagent scope](</docs/en/sub-agents#choose-the-subagent-scope>): project, user, plugin, or CLI-defined. This lets you define a role once, such as a security-reviewer or test-runner, and reuse it both as a delegated subagent and as an agent team teammate. To use a subagent definition, name it when you ask Claude to spawn the teammate: Spawn a teammate using the security-reviewer agent type to audit the auth module. -The teammate honors that definition’s `tools` allowlist and `model`, and the definition’s body is appended to the teammate’s system prompt as additional instructions rather than replacing it. For an in-process teammate, Claude Code adds `SendMessage` to that allowlist. In a [session that has the Task tools](</docs/en/tools-reference#task-tool-availability>), Claude Code adds `TaskCreate`, `TaskGet`, `TaskList`, and `TaskUpdate` to it too. - -The `skills` and `mcpServers` frontmatter fields in a subagent definition are not applied when that definition runs as a teammate. Teammates load skills and MCP servers from your project and user settings, the same as a regular session. +Claude Code reads the subagent definition you named and applies these parts of it to the teammate. Where a part depends on the teammate’s display mode, the entry says so: + + * **`tools`** : Claude Code limits the teammate to the tools in the definition’s `tools` list. For an in-process teammate, Claude Code adds `SendMessage` to that list, and in a [session that has the Task tools](</docs/en/tools-reference#task-tool-availability>) it adds `TaskCreate`, `TaskGet`, `TaskList`, and `TaskUpdate` too. + * **`model`** : for an in-process teammate, Claude Code uses the definition’s `model` when neither `CLAUDE_CODE_SUBAGENT_MODEL` nor your spawn prompt names a model. A split-pane teammate doesn’t use the definition’s `model`. See how Claude Code picks a teammate’s model. + * **Body** : for an in-process teammate, Claude Code appends the definition’s body to its default system prompt as additional instructions. For a split-pane teammate, Claude Code uses the body in place of its default system prompt. + * **`skills`** : Claude Code doesn’t apply the definition’s `skills` to a teammate in either display mode. The teammate loads skills from your project and user settings. + * **`mcpServers`** : for a split-pane teammate, Claude Code applies the definition’s `mcpServers` under the [rules for that field](</docs/en/sub-agents#scope-mcp-servers-to-a-subagent>), which cover a session started with `--agent` as well. An in-process teammate ignores the field and loads MCP servers from your project and user settings. ### @@ -520,4 +528,5 @@ Explore related approaches for parallel work and delegation: * **Lightweight delegation** : [subagents](</docs/en/sub-agents>) spawn helper agents for research or verification within your session, better for tasks that don’t need inter-agent coordination + * **Messaging between your own sessions** : [cross-session messaging](</docs/en/cross-session-messaging>) lets Claude pass findings between the sessions you run yourself * **Manual parallel sessions** : [Git worktrees](</docs/en/worktrees>) let you run multiple Claude Code sessions yourself without automated team coordination
modified Manage multiple agents with agent view View current →
Show diff (215 lines)
--- a/agent-view.md +++ b/agent-view.md @@ -91,17 +91,17 @@ Idle| Dimmed| The session has nothing to do and is ready for your next prompt Completed| Green| The task finished successfully Failed| Red| The task ended with an error -Stopped| Grey| The session was stopped with `Ctrl+X` or `claude stop`, or its process was ended from outside Claude Code +Stopped| Grey| You stopped the session with `Ctrl+X` or `claude stop`, its process was ended from outside Claude Code, or it ended while the background service was off Separately, the icon’s shape shows whether the underlying process is running: Shape| What it means ---|--- `✻` or animated `✽`| The session process is alive and replies immediately -`∙`| The process has exited. You can still peek, reply, or attach, and Claude restarts from where it left off +`∙`| The process has exited. You can still peek at the row, and when you reply or attach, 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 `#N` or `!N` label that can appear at the right edge of a row is a link to the session’s pull request or merge request, 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. 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-reference#preferrednotifchannel>) 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. A session that was mid-response when the machine slept can come back unresponsive. When you open a session that has stopped responding, the supervisor restarts its process and the session continues the interrupted response from where it left off. +The `#N` or `!N` label that can appear at the right edge of a row is a link to the session’s pull request or merge request, 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. 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-reference#preferrednotifchannel>) 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 or stopped after shutdown for how to recover them. A session that was mid-response when the machine slept can come back unresponsive. When you open a session that has stopped responding, the supervisor restarts its process and the session continues the interrupted response from where it left off. ### @@ -152,7 +152,7 @@ * A finished session: its result * A working session: its full status sentence -Any pull requests linked to the session are listed next. For a session that’s waiting on you, a line such as `waiting 3m` below them shows how long it has been waiting, and it’s the only time shown in the panel. The age at the right edge of the row is a different number: it counts from when the session started. Most of the time the peek panel is enough and you don’t need to open the full transcript. Type a reply in the peek panel and press `Enter` to send it to that session. When the session asks a question with predefined choices, the peek panel shows them as a numbered list and you can press a number key to pick one. A permission prompt shows as text describing what the session wants to run, without numbered options. Type a reply to answer it, or attach to answer with the standard prompt. For other blocked sessions, press `Tab` to fill the input with a suggested reply you can edit before sending. Prefix a reply with `!` to send a Bash command instead. A reply that can’t be delivered, because the background service is unreachable or the send fails, is saved and sent to the session as its next prompt when its process starts again, and the error message says the reply was saved. A reply prefixed with `!` isn’t saved, because the saved text would reach the session as a plain prompt rather than run as a Bash command. With [voice dictation](</docs/en/voice-dictation>) enabled, hold or tap your push-to-talk key while the reply input is focused to dictate a reply instead of typing it. The same works in the dispatch input at the bottom of agent view. Use `↑` and `↓` to peek at adjacent sessions without closing the panel, or `→` to attach. +Any pull requests linked to the session are listed next. For a session that’s waiting on you, a line such as `waiting 3m` below them shows how long it has been waiting, and it’s the only time shown in the panel. The age at the right edge of the row is a different number: it counts from when the session started. Most of the time the peek panel is enough and you don’t need to open the full transcript. Type a reply in the peek panel and press `Enter` to send it to that session. When the session asks a question with predefined choices, the peek panel shows them as a numbered list and you can press a number key to pick one. A permission prompt shows as text describing what the session wants to run, without numbered options. Type a reply to answer it, or attach to answer with the standard prompt. For other blocked sessions, press `Tab` to fill the input with a suggested reply you can edit before sending. Prefix a reply with `!` to send a Bash command instead. When a [`PermissionRequest`](</docs/en/hooks#permissionrequest>) or [`PreToolUse`](</docs/en/hooks#pretooluse>) hook returns output Claude Code can’t validate for the call the session is asking about, the row shows the hook event and `hook output invalid:` with the validation error before the pending request’s text. For a hook that fails another way, the row says the hook failed. The session still waits on the same request. A reply that can’t be delivered, because the background service is unreachable or the send fails, is saved and sent to the session as its next prompt when its process starts again, and the error message says the reply was saved. A reply prefixed with `!` isn’t saved, because the saved text would reach the session as a plain prompt rather than run as a Bash command. With [voice dictation](</docs/en/voice-dictation>) enabled, hold or tap your push-to-talk key while the reply input is focused to dictate a reply instead of typing it. The same works in the dispatch input at the bottom of agent view. Use `↑` and `↓` to peek at adjacent sessions without closing the panel, or `→` to attach. ### @@ -174,7 +174,7 @@ * Press `Esc` to undo the switch and return to the conversation. If `Esc` shows `Still starting — try again in a moment`, the background session isn’t ready yet, so press `Esc` again in a moment. * Press `Ctrl+C` twice to exit to your shell. -When Claude Code can’t reopen the conversation, it exits and prints a `claude --resume` command that resumes it. [Claude’s task list](</docs/en/interactive-mode#task-list>) moves to the background session with the conversation, so the checklist is intact when you return to that row. The row you pressed `←` from also keeps a bold, undimmed name after you move the selection with the arrow keys or the mouse, so you can tell which session you came from. If a tool is running when you press `←`, Claude Code waits up to about ten seconds for it to finish before backgrounding, and the response continues in the background session. Press `←` again to background immediately instead of waiting. When in-flight work can’t carry over to the background session, the `Background this session?` dialog appears first, the same as with `/background`. The ten-second limit doesn’t apply while [subagents](</docs/en/sub-agents>) are running. Claude Code keeps waiting so their work carries over, and shows a `Still backgrounding after the current tool` notice while it waits; press `←` again to background without waiting, which restarts the subagents from the beginning. Claude Code doesn’t background the session while you have unsent text in the prompt input, because the text stays in your terminal’s input box and wouldn’t move to the background session. If you type into the input while Claude Code waits to background the session, it cancels the switch with `Backgrounding cancelled — you have unsent text in the input. Send it or clear it, then press ← again.` Pressing `←` creates the session’s row even when the conversation has no messages yet, so `→` still returns to it. You can turn this shortcut off with the `leftArrowOpensAgents` setting in `/config`. +When Claude Code can’t reopen the conversation, it exits and prints a `claude --resume` command that resumes it. [Claude’s task list](</docs/en/interactive-mode#task-list>) moves to the background session with the conversation, so the checklist is intact when you return to that row. The row you pressed `←` from also keeps a bold, undimmed name after you move the selection with the arrow keys or the mouse, so you can tell which session you came from. If a tool is running when you press `←`, Claude Code waits up to about ten seconds for it to finish before backgrounding, and Claude continues the response in the background session. Press `←` again to background immediately instead of waiting. When in-flight work can’t carry over to the background session, Claude Code shows the `Background this session?` dialog first, the same as with `/background`. The ten-second limit doesn’t apply while the [foreground subagents](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) Claude started in the conversation are still running. Claude Code keeps waiting so their work carries over, and shows a `Still backgrounding after the current tool` notice while it waits. Press `←` again to background without waiting, which restarts those subagents from the beginning. Claude Code doesn’t wait for the subagents a [dynamic workflow](</docs/en/workflows>) is running. When a workflow has subagents running, Claude Code shows the `Background this session?` dialog instead. Claude Code doesn’t background the session while you have unsent text in the prompt input, because the text stays in your terminal’s input box and wouldn’t move to the background session. If you type into the input while Claude Code waits to background the session, it cancels the switch with `Backgrounding cancelled — you have unsent text in the input. Send it or clear it, then press ← again.` Pressing `←` creates the session’s row even when the conversation has no messages yet, so `→` still returns to it. You can turn this shortcut off with the `leftArrowOpensAgents` setting in `/config`. ### @@ -226,7 +226,8 @@ `↑` / `↓`| Move between rows `Enter`| Attach to the selected session, or dispatch if there’s text in the input `Space`| Open or close the peek panel for the selected session -`Shift+Enter`| Dispatch and attach immediately +`Shift+Enter`| Insert a newline in the dispatch input, [as in the main prompt](</docs/en/terminal-config#enter-multiline-prompts>) +`Ctrl+Enter`| Dispatch and attach immediately, in terminals where the `?` overlay lists `ctrl+enter to start and open` `→`| Attach to the selected session `Alt+1`..`Alt+9`| Attach to session 1–9 in the focused session’s directory `Tab`| On an empty input, browse all subagents. Otherwise apply the highlighted suggestion @@ -265,7 +266,6 @@ `/<command>`| Suggest [skills](</docs/en/skills>) and [commands](</docs/en/commands>) to dispatch as the prompt `! <command>`| Run a shell command as a background job instead of starting a Claude session. The job appears as a row you can attach to, watch, and detach from `#<number>` or a pull or merge request URL| If a session is already working on that pull request or merge request, Claude Code selects its row instead of dispatching a new session -`Shift+Enter`| Dispatch and immediately attach to the new session A small set of commands run in agent view itself instead of dispatching: @@ -309,7 +309,7 @@ Send the session to the background -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 a 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. Choose `Move to background and exit` to background the session the same way `/background` does and return to your shell. The option isn’t shown when agent view is turned off. +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 a 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. Choose `Move to background and exit` to background the session the same way `/background` does and return to your shell. The option isn’t shown when agent view is turned off. If a background session on the list already has the conversation’s name, Claude Code numbers the new row’s name, such as `my-session (2)`, and leaves the existing row’s name alone. To rename the new row, select it in agent view and press `Ctrl+R`. #### @@ -332,7 +332,7 @@ What carries over when you background -Backgrounding 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>) all carry over 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. 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, and 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: +Backgrounding 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, scheduled tasks you created with [`/loop`](</docs/en/scheduled-tasks>), and Claude’s [automatic replies to artifact comments](</docs/en/artifacts#let-claude-reply-to-comments-on-its-own>) all carry over 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. 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. When a [dynamic workflow](</docs/en/workflows>) still has subagents running, Claude Code asks before backgrounding with the `Background this session?` dialog, which says how many subagents would restart. Choose `Stay` to let them finish first. If you confirm, Claude Code replays the run in the background session: subagents that were still running start over from the beginning, so the tokens they used so far are spent again. See [Resume after a pause](</docs/en/workflows#resume-after-a-pause>) for which completed subagents return their saved results and which run again. Claude Code stops work that can’t carry over, such as a running [monitor](</docs/en/tools-reference#monitor-tool>), and stops a backgrounded subagent that owns a monitor along with it. When any such work is running, Claude Code shows the `Background this session?` dialog so you can confirm before it stops the work. 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` @@ -420,8 +420,8 @@ * Agent view removes it, including uncommitted changes, so commit what you want to keep first. * `claude rm` keeps it, along with the session row, when it has uncommitted changes. - * Neither path removes one with unpushed commits, or one that another running session claims or has locked: Claude Code keeps the worktree and the session and names the kept path and the reason. In agent view, a refused delete shows `not deleted` with the reason on the session’s row. Push the commits or close the other session, then delete again. - * One git no longer recognizes, for example after `git worktree prune`, doesn’t block the delete: the session is deleted and the directory stays on disk. + * Neither agent view nor `claude rm` removes a worktree with commits Claude Code can’t confirm are saved elsewhere, or one that another running session is using or has locked. Claude Code keeps the worktree and the session, and names the kept directory and the reason. Commits on a remote don’t block the delete. Neither do commits on the local copy of your `origin` remote’s default branch, as long as that branch is checked out in your main checkout, the repository directory itself rather than a worktree. In agent view, a refused delete shows `not deleted` with the reason on the session’s row. Push the commits, merge them into that default branch, or close the other session, then delete again. + * A worktree git no longer recognizes, for example after `git worktree prune`, doesn’t block the delete. Claude Code deletes the session and leaves the directory on disk. A worktree you created yourself and started the session inside is left in place either way. A session whose worktree directory belongs to no git repository, because the repository was deleted or a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) created the directory elsewhere, can still be deleted. While files remain in the directory: @@ -535,7 +535,7 @@ `claude attach <id>`| Attach to a session in this terminal `claude logs <id>`| Print the session’s recent output `claude stop <id>`| Stop a session. Also accepts `claude kill` -`claude respawn <id>`| Restart a session, running or stopped, with its conversation intact, e.g. to pick up an updated Claude Code binary +`claude respawn <id>`| Restart a session, running or stopped, e.g. to pick up an updated Claude Code binary. The restarted session resumes its saved conversation; when none is on disk, it runs its original prompt again as a new conversation `claude respawn --all`| Restart every running session, e.g. to move all sessions onto an updated Claude Code binary at once `claude rm <id>`| Remove a session from the list, along with a worktree Claude created for it when that’s safe to delete; see What deleting a session removes. The conversation transcript stays on your local machine and remains available through `claude --resume` `claude daemon status`| Print the supervisor’s state, version, socket directory, and worker count @@ -577,7 +577,7 @@ * The supervisor was started from an environment with the same gateway. The supervisor captures its environment from the first shell that opens agent view or dispatches a background session, so starting from the gateway shell gives it that environment. * The session is dispatched into the directory you’re dispatching from, or is your own session backgrounded with `←` or `/background`. Dispatching into a different directory with `@repo` or `--cwd` doesn’t carry the shell’s gateway; that project’s `settings.json` `env` block supplies the endpoint instead. -When the supervisor’s environment carries a different gateway or none, the worker keeps your stored credentials against the default endpoint instead of mixing one environment’s credential with another’s endpoint. The forwarded endpoint applies only to that live process and is never written to disk. When the supervisor stops an idle session and you later wake it by attaching, peeking, or replying, your environment’s gateway is forwarded again under the same conditions as a fresh dispatch. Waking a session from a shell without the gateway restarts it against your settings and stored credentials instead. 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. The supervisor counts a running background shell command, subagent, dynamic workflow, or monitor 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. This also applies to a conversation you backgrounded with `←` or `/background` and then left idle with nothing running. The supervisor also restarts a session whose process exits unexpectedly, with three safeguards so a restart never overrides a stop or acts on stale input: +When the supervisor’s environment carries a different gateway or none, the worker keeps your stored credentials against the default endpoint instead of mixing one environment’s credential with another’s endpoint. The forwarded endpoint applies only to that live process and is never written to disk. When the supervisor stops an idle session and you later wake it by attaching or replying, your environment’s gateway is forwarded again under the same conditions as a fresh dispatch. Waking a session from a shell without the gateway restarts it against your settings and stored credentials instead. 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. The supervisor counts a running background shell command, subagent, dynamic workflow, or monitor 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 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. This also applies to a conversation you backgrounded with `←` or `/background` and then left idle with nothing running. The supervisor also restarts a session whose process exits unexpectedly, with three safeguards so a restart never overrides a stop or acts on stale input: * A session whose state on disk already shows it as done, failed, or stopped isn’t restarted, unless a reply you sent is still waiting to be delivered. * Ending the process of a session you backgrounded with `←` or `/background` yourself, for example with `kill`, marks the session stopped instead of restarting it. A session dispatched with a task, from the agent view input or `claude --bg`, is still restarted so the dispatched work completes. @@ -586,7 +586,7 @@ 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 dynamic workflow resumes the same way it does when you background the session: subagents that were still running start over * A [background subagent](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) resumes from its own transcript 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`. A restarted process finds the conversation of a session that moved into a worktree mid-task: when the transcript isn’t where the session started, Claude Code also looks under the repository’s registered worktrees. When neither the session’s own directory nor those worktrees has the transcript, Claude Code scans all your saved session transcripts as a last resort and resumes from the one that matches the session. 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. Once the new supervisor takes over, it also restarts the remaining idle sessions onto the new version, a few at a time in the background, after a short delay that lets terminals attached across the restart reconnect first. A session that is working, waiting on your input, or has a terminal attached isn’t interrupted; it moves to the new version the next time its process restarts. These restarts only ever move a session onto a newer version. A supervisor running an older Claude Code version than the one a session’s process was started with leaves that process alone; the session keeps running the newer version until a newer supervisor takes over. Running `claude attach` while the supervisor is restarting a session, whether for an update, a stall, or a migration, waits for the replacement process instead of failing. A status line such as `Agent is updating to the new Claude Code…` names what it’s waiting for and counts the elapsed seconds, and the command connects as soon as the session is ready. After about 60 seconds it stops waiting and reports an error. `claude attach` also waits while the background service itself is starting or reconnecting, and a session that finished during that wait is reported as exited rather than as an error. A terminal resize you make during a slow attach is applied when the attach completes. @@ -644,7 +644,13 @@ Backgrounding shows a `Background this session?` dialog -If pressing `←` to background the current session shows a `Background this session?` dialog, the session has in-flight work that can’t move to the background session, such as a running [monitor](</docs/en/tools-reference#monitor-tool>), and Claude Code won’t silently stop it. The dialog names the work that will be stopped and, separately, counts the tasks that carry over. Run `/tasks` to see everything that’s running, then confirm to background anyway or choose `Stay` to let the work finish first. See What carries over when you background for which task kinds carry over and which are stopped. +If you press `←` to background the current session and Claude Code shows a `Background this session?` dialog, the session has in-flight work that backgrounding would stop, restart, or leave running unattended, and Claude Code asks before it does any of those: + + * **Work that can’t move** : the session has work that can’t move to the background session, such as a running [monitor](</docs/en/tools-reference#monitor-tool>). The dialog names the work Claude Code would stop and, separately, counts the tasks that carry over. + * **A workflow with running subagents** : a [dynamic workflow](</docs/en/workflows>) still has subagents running. The workflow itself carries over, but its running subagents restart from the beginning, and the dialog says how many. + * **Automatic artifact replies** : Claude is [replying to comments on an artifact on its own](</docs/en/artifacts#let-claude-reply-to-comments-on-its-own>). Those replies continue in the background session, and the dialog says so. + +Run `/tasks` to see everything that’s running, then confirm to background anyway or choose `Stay` to let the work finish first. See What carries over when you background for which kinds of work carry over and which Claude Code stops. ### @@ -658,9 +664,14 @@ ​ -Sessions show as failed after shutdown - -Shutting down or restarting your machine stops running background sessions, so they show as failed when you next open agent view. Attach, peek, or reply to any of them and the session restarts from where it left off. Sleep alone doesn’t cause this. Sessions are preserved across sleep and the supervisor reconnects to them on wake. +Sessions show as failed or stopped after shutdown + +Shutting down or restarting your machine stops running background sessions. A session that was waiting on your input stays under `Needs input` when you come back. For any other running session, what agent view shows depends on how long ago it last made progress: + + * Within 48 hours, the session shows as failed. Attach or reply to it and it restarts from where it left off. + * Past 48 hours, such as after the machine was off for days, the session shows as stopped with `ended while the background service was off`. Press `Enter` on the row and the footer shows `Press enter again to resume this session (it ended while the background service was off), or ctrl+x to delete it.` Press `Enter` on the same row again to resume its saved conversation. A reply, or `claude attach <id>`, resumes it without that footer prompt. + +When [transcript cleanup](</docs/en/settings-reference#cleanupperioddays>) has removed a stopped session’s saved conversation, Claude Code refuses to open the row: the message says there is nothing to resume. `claude rm <id>` deletes the row, except in the kept cases described above, and `claude respawn <id>` runs its original prompt again. See [This session’s saved conversation is no longer on disk](</docs/en/errors#this-sessions-saved-conversation-is-no-longer-on-disk>). Sleep alone doesn’t stop sessions. Sessions are preserved across sleep and the supervisor reconnects to them on wake. ### @@ -668,7 +679,12 @@ Opening a session says the conversation is already open -Opening a stopped row whose conversation is also held open by another running non-interactive Claude Code process, for example a background worker for the same conversation that is still winding down, shows `This conversation is already open in another running Claude session` instead of starting the row’s process, because two processes can’t write to the same transcript. Reply in the session that already has the conversation open, or exit it and open the row again. A reply you typed with the refused attempt isn’t lost; it’s sent the next time the session starts. +Two processes can’t write to the same transcript. When a stopped session’s saved conversation is already open in another live Claude Code process, Claude Code refuses to start the session’s own process. What you see depends on what holds the conversation: + + * A terminal where you resumed the conversation, for example with `claude --resume` or `/resume`: the row shows `Open in a terminal` with a hint to continue it there, and opening the row shows `Can't open — this session is running in another terminal`. Continue in that terminal, or exit it and open the row again. + * Another non-interactive Claude Code process, for example a background session process for the same conversation that hasn’t exited yet: opening the row shows `This conversation is already open in another running Claude session`. Use that process, or wait for it to exit and open the row again. + +Claude Code saves a reply you typed with the refused attempt and sends it the next time the session starts. ### @@ -714,7 +730,7 @@ A session fails before starting with a `possibly low memory` note -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`. 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. +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`. 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 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. ### @@ -790,9 +806,10 @@ Related resources -For other ways to run Claude in parallel, see: +For other ways to run Claude in parallel, and for passing findings between the sessions you run, see: * [Run agents in parallel](</docs/en/agents>): compare agent view with subagents, agent teams, and worktrees + * [Cross-session messaging](</docs/en/cross-session-messaging>): have your sessions pass findings to each other * [Agent teams](</docs/en/agent-teams>): coordinate multiple sessions that message each other * [Claude Code on the web](</docs/en/claude-code-on-the-web>): run sessions in a managed cloud environment instead of locally @@ -806,7 +823,22 @@ Version| Change ---|--- +v2.1.248| `Shift+Enter` in the dispatch input inserts a newline, matching the main prompt, and `Ctrl+Enter` dispatches and attaches immediately in terminals where the `?` overlay lists `ctrl+enter to start and open`. Before this release, `Shift+Enter` dispatched and attached. +v2.1.248| Deleting a session succeeds when the worktree’s commits are already on the local copy of your `origin` remote’s default branch and your main checkout has that branch checked out; before this release, the delete was refused with `has commits that are not pushed anywhere`. +v2.1.248| A session backgrounded with `←` or `/background` holds the [`git worktree lock`](</docs/en/worktrees#clean-up-subagent-and-background-session-worktrees>) on its worktree while it runs; before this release, backgrounding released the lock, and cleanup or `git worktree remove` could remove the worktree under the running session. +v2.1.248| A background session that wasn’t waiting on your input and is found dead more than 48 hours after its last activity, such as after the machine was off for days, shows as stopped with `ended while the background service was off`, and `Enter` on it asks before resuming its saved conversation. Before this release, such a session reappeared as a fresh failure sorted to the top of the list, and a single `Enter` pulled the weeks-old conversation into the foreground. +v2.1.248| Opening a stopped row whose conversation you resumed in another terminal is refused with `Can't open — this session is running in another terminal`, and the row shows `Open in a terminal` instead of showing under `Working`. Before this release, opening the row started a second process writing to the same conversation. +v2.1.248| A background session waiting on a permission decision while a `PermissionRequest` or `PreToolUse` hook printed an invalid answer names the hook event and the schema error on its row. Before this release, the row showed only the pending request. +v2.1.248| On Windows, `claude agents` responds to the keyboard when launched in a terminal tab that an earlier program left in win32-input-mode. Before this release, Claude Code didn’t decode the key records such a tab sends. v2.1.247| On Linux and WSL, a session whose terminal host process died fails within seconds with the reason. An open that produces no output ends after about ten seconds with a restart offer, and `Enter` on the row restarts the session with its conversation; `claude attach <id>` reports the cause and exits. Before this release, opening such a session showed `opening… · esc to cancel` indefinitely and `claude attach <id>` waited without reporting an error. +v2.1.246| On an npm installation, when the background service fails to start while `npm install -g @anthropic-ai/claude-code` is replacing the binary, Claude Code waits up to ten seconds for the install to finish and retries before reporting [`EACCES: permission denied`](</docs/en/errors#eacces-when-starting-a-background-session>). +v2.1.246| When the background service process dies after printing an error, Claude Code reports the failure and [quotes the service’s first error line](</docs/en/errors#background-service-exited-before-it-became-reachable>). +v2.1.246| If your machine sleeps while the background service is starting, Claude Code retries the start once instead of failing. +v2.1.246| Claude Code waits about two minutes instead of 45 seconds for a newly started background service that is alive but slow to accept connections. +v2.1.246| The background service starts from your home directory, so on macOS and Linux a starting directory that was deleted or moved no longer blocks the start. +v2.1.246| `/fork` copies the full conversation from a session that itself started as a copy and hasn’t recorded a new prompt since: a `/fork` copy you attached to, a session reattached after `←` or `/background` moved it to the background, or a session started with `claude --resume <id> --fork-session`. Before this release, if you ran `/fork` in such a session before sending it a new prompt, Claude Code printed the normal confirmation but started the copy with an empty conversation. Moving such a session to the background with `←` or `/background` lost the conversation the same way. +v2.1.246| When you open a session you just dispatched while its worker process is still starting, such as by pressing `Enter` on its row, Claude Code waits for the process and then attaches. Before this release, if you pressed `Enter` while the process was still starting, Claude Code could stop the session with [`Session <id> was stopped while the respawn was in flight`](</docs/en/errors#session-was-stopped-while-the-respawn-was-in-flight>). +v2.1.246| When you background a named session, Claude Code lists it once, and when you background the same conversation again, it numbers the new row’s name, such as `my-session (2)`, with the existing row keeping its name. Before this release, the terminal you pressed `←` in could appear in `claude agents --json` as a second session under the same name, and if you backgrounded the same conversation again, Claude Code added another row under the identical name. v2.1.239| With [vim editor mode](</docs/en/interactive-mode#vim-editor-mode>) on, pressing `Esc` in agent view’s input switches from INSERT to NORMAL mode and keeps your text, matching the main prompt; in NORMAL mode with text still in the input, pressing `Esc` clears it, and pressing `Esc` on an empty input exits, as the `Esc` shortcut describes. Before this release, `Esc` cleared the input. v2.1.233| For a session linked to a GitLab merge request, Claude Code writes the row’s label in GitLab’s `!1234` reference syntax. You can also paste the merge request’s URL into the dispatch input to select that session. Before this release, the label rendered as `#1234`, and a pasted merge request URL matched a session only when its first prompt contained the URL. v2.1.227| Deleting a session keeps the session and its worktree while another live Claude Code session is running inside that worktree directory. Agent view shows `not deleted` on the row and the reason in the footer, and `claude rm` prints `kept <id>` with the reason, which names the other session’s process ID. Before this release, deleting the session removed the worktree while the other session was still working in it. @@ -833,7 +865,7 @@ v2.1.214| A session backgrounded with `←` or `/background` and left idle with nothing running has its process stopped like any other idle session, instead of keeping its process and the background service running indefinitely. A completed session can be removed with `claude rm` or from agent view after the background service has gone idle, and a session that entered a worktree after being dispatched from a directory that isn’t a git repository, such as a multi-repo workspace folder, can be deleted from agent view when the worktree itself belongs to a git repository, because the cleanup is resolved from the worktree instead of the directory the session was dispatched from; both removals were refused on every attempt before. Reopening a stopped session restores its saved conversation even when a folder in the transcript store can’t be read. v2.1.213| `/install-github-app`, the [`/mcp`](</docs/en/mcp>) settings list, and MCP authentication actions work in a background session while a terminal is attached, and are refused only when nobody is attached, with a message telling you to attach and run the command again; from v2.1.208 through v2.1.212 they were refused even with a terminal attached. v2.1.212| `/fork` in an interactive session copies the conversation into a new background session that appears as its own row, named after the session it came from or, for a prompted fork of an unnamed session, after the fork prompt, while the original keeps running; the earlier forked-subagent behavior of `/fork` moved to `/subtask`. With agent view turned off, `/fork` keeps the forked-subagent behavior. A focused row that is waiting for its first prompt shows `space to send it a prompt`. `Ctrl+J` inserts a newline in the dispatch input on terminals with extended key reporting, where the keypress was previously ignored, and the `?` overlay lists the shortcut. The `←` footer hint in an interactive session briefly shows `N done` when a background session finishes while none need your input. Typing a bare `/resume` in agent view opens a picker of past sessions of the repository you opened agent view from, including sessions deleted from the list, and picking one resumes it as a background session; before this release `/resume` wasn’t available in agent view and deleted sessions were reachable only with `claude --resume` or `/resume` from an interactive session. Targeted, scoped, and restricted forms keep the `attach to a session to run it` hint that earlier versions showed for every form. Sessions waiting on a sandbox network-host prompt, an MCP input request, or a managed-settings prompt show as `Needs input` instead of `Working`, in agent view and in `claude agents --json`, and a question from Claude reports `waitingFor: input needed` instead of `permission prompt`. Attaching to a session whose process has stopped shows its transcript formatted the way the live session renders it, instead of as raw text. A stopped session whose transcript is in an unexpected place resumes from it via a last-resort scan of your saved transcripts, and opening a row that has no saved transcript shows `Press enter again to restart this session fresh`, restarting it fresh on the second press; v2.1.211 showed the refusal with no way to restart from agent view. -v2.1.211| Waking a stopped session by attaching, peeking, or replying from the directory it runs in forwards your shell’s gateway `ANTHROPIC_BASE_URL` again, under the same conditions as a fresh dispatch, so a session authenticated through a gateway `ANTHROPIC_AUTH_TOKEN` resumes on the gateway instead of reporting `Not logged in`. Attaching to a stopped session that was backgrounded from another conversation before its first response finished is refused with `This session has no saved transcript` instead of silently starting a blank conversation under the same session id; opening the same row from agent view showed the refusal in the footer. Ending the process of a `←` or `/background` session from outside Claude Code marks it stopped instead of the supervisor restarting it, a stop already recorded on disk is honored unless a reply you sent is still waiting to be delivered, a session restarted after a crash is told it was restarted, and a restarted `←` or `/background` session doesn’t resume an interrupted response older than about an hour. A session-naming reply that answers or refuses the prompt instead of labeling it, such as for a prompt that’s mostly a link, is discarded and the row keeps a name taken from the prompt text. Deleting a session whose worktree git no longer recognizes succeeds, leaving the worktree directory on disk and naming its path, instead of every attempt being refused. A refused delete shows the reason on the session’s row, including the underlying git error when the worktree couldn’t be removed, instead of the row silently reappearing. +v2.1.211| Waking a stopped session by attaching or replying from the directory it runs in forwards your shell’s gateway `ANTHROPIC_BASE_URL` again, under the same conditions as a fresh dispatch, so a session authenticated through a gateway `ANTHROPIC_AUTH_TOKEN` resumes on the gateway instead of reporting `Not logged in`. Attaching to a stopped session that was backgrounded from another conversation before its first response finished is refused with `This session has no saved transcript` instead of silently starting a blank conversation under the same session id; opening the same row from agent view showed the refusal in the footer. Ending the process of a `←` or `/background` session from outside Claude Code marks it stopped instead of the supervisor restarting it, a stop already recorded on disk is honored unless a reply you sent is still waiting to be delivered, a session restarted after a crash is told it was restarted, and a restarted `←` or `/background` session doesn’t resume an interrupted response older than about an hour. A session-naming reply that answers or refuses the prompt instead of labeling it, such as for a prompt that’s mostly a link, is discarded and the row keeps a name taken from the prompt text. Deleting a session whose worktree git no longer recognizes succeeds, leaving the worktree directory on disk and naming its path, instead of every attempt being refused. A refused delete shows the reason on the session’s row, including the underlying git error when the worktree couldn’t be removed, instead of the row silently reappearing. v2.1.210| `claude attach` waits while the background service is starting or reconnecting instead of failing with a `job not found` or `still starting` error, reports a session that finished during the attach as exited, and applies a terminal resize made during a slow attach when the attach completes. The prompt footer’s `←` needs-input count appears on every provider, including third-party providers that previously showed the plain `← for agents` form. Backgrounding a session with `←` carries Claude’s task list to the background session instead of dropping it. The row you pressed `←` from keeps a bold, undimmed name after the selection moves. `claude agents --effort` accepts `ultracode` instead of silently dropping it. v2.1.208| Attaching to a session whose process has stopped shows the last screenful of its transcript while the process starts, instead of only a `Session is starting` note. A reply that can’t be delivered because the background service is unreachable or the send fails is saved and sent as the session’s next prompt when its process starts again; before this release, a reply lost while the background service was unreachable was discarded. A process whose own binary was replaced by an update can still start the supervisor, from the installed `claude` launcher or the newest version on disk, instead of failing until Claude Code was restarted. A supervisor running an older version never restarts an idle session started by a newer version onto its own older binary. Deleting a session removes its worktree even after the session moved the worktree onto a different branch, and keeps the worktree together with the session row when the worktree has commits that aren’t pushed anywhere or another session claims it, instead of destroying the commits or orphaning the worktree. `/install-github-app` and the `/mcp` settings list and its authentication actions are refused in a background session with a message naming the alternative; in v2.1.208 only, the `/model` picker was refused the same way and a typed `/model <name>` switched that session only instead of also saving your default model. v2.1.207| The peek panel opens with the sentence the row truncates, such as the exact question for a session that’s waiting on you, and shows how long a blocked session has been waiting as a single `waiting 3m` line instead of prefixing the same timestamp to the status sentence and the question. Pasting the same text again in the dispatch input expands the collapsed `[Pasted text #N]` placeholder instead of adding a second one. A background session named by accepting a plan shows that name on its row. A background session that moved into a worktree keeps its conversation when its process is restarted from agent view.
modified Run agents in parallel View current →
--- a/agents.md +++ b/agents.md @@ -34,7 +34,7 @@ * You hand off independent tasks and check back later: [agent view](</docs/en/agent-view>) * Claude plans, assigns, and supervises a group of workers: [agent teams](</docs/en/agent-teams>), experimental and disabled by default * A script holds the plan instead of Claude’s turn-by-turn judgment: [dynamic workflows](</docs/en/workflows>). See [how workflows compare to subagents and skills](</docs/en/workflows#when-to-use-a-workflow>) - * **Do the workers need to talk to each other?** Subagents report results back to the conversation that spawned them, and agent view sessions report only to you, though separate sessions can pass messages with [cross-session messaging](</docs/en/cross-session-messaging>). Teammates in an agent team message each other directly and, when they [have the Task tools](</docs/en/tools-reference#task-tool-availability>), share a task list. + * **Do the workers need to talk to each other?** Claude can pass findings with [cross-session messaging](</docs/en/cross-session-messaging>) between sessions you run yourself, including the sessions you dispatch from agent view. Subagents report results back to the conversation that spawned them, and agent view sessions report results only to you. Teammates in an agent team message each other directly and, when they [have the Task tools](</docs/en/tools-reference#task-tool-availability>), share a task list. * **Do the tasks touch the same files?** Isolate the work with [worktrees](</docs/en/worktrees>). Subagents and sessions you run yourself can each use a separate worktree. Agent teams don’t isolate teammates in worktrees, so [partition the work](</docs/en/agent-teams#avoid-file-conflicts>) so each teammate owns a different set of files. ##
modified Share session output as artifacts View current →
--- a/artifacts.md +++ b/artifacts.md @@ -39,7 +39,18 @@ Build a dashboard artifact of last week's deploy failures by service and keep it updated as you investigate. -Claude writes the page to an HTML or Markdown file in your project, then publishes it. Before publishing a new artifact, Claude Code asks for permission; it might say something like `Claude wants to publish "Deploy failures by service" (deploy-failures.html) to a private page on claude.ai`. Republishing an artifact you have already approved does not prompt again. Select **Yes** to publish. Claude prints the URL, and your browser opens to the new page. Press `Ctrl+]` at any time to reopen the most recent artifact from the terminal. Claude picks the artifact’s title and an emoji for its browser-tab icon. Both appear in your gallery of artifacts on claude.ai and in shared links, so ask Claude to use a specific title or icon if you want one. To stop the browser from opening automatically when a new artifact is published, set `CLAUDE_CODE_ARTIFACT_AUTO_OPEN=0` in your environment. If Claude responds that it cannot publish, or writes a local HTML file without a link, the tool is not enabled for your session. Check the Availability requirements. +Unless you name a location, Claude writes the page to an HTML or Markdown file in a temporary directory outside your project, then publishes it. Publishing a new artifact goes through your session’s [permission mode](</docs/en/permission-modes>): + + * **Auto mode** : the classifier reviews the publish instead of prompting you, so Claude can publish a page without you seeing a prompt. Which mode your sessions start in depends on your plan; see [the starting permission mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). + * **Manual and Accept edits modes** : Claude Code asks for permission; it might say something like `Claude wants to publish deploy-failures.html, uploading it to claude.ai (Anthropic's servers) to host as the page "Deploy failures by service", private to you until you share it`. Select **Yes** to publish. + +After you approve an artifact once, Claude Code republishes it without asking, and asks again in some cases, including when: + + * Claude declares a runtime capability for the page, such as connector calls + * You have since shared it publicly + * You have since shared it with specific people or your organization with the latest version chosen as the version viewers see + +After the first publish, Claude prints the URL, and your browser opens to the new page. Press `Ctrl+]` at any time to reopen the most recent artifact from the terminal. Claude picks the artifact’s title and an emoji for its browser-tab icon. Both appear in your gallery of artifacts on claude.ai and in shared links, so ask Claude to use a specific title or icon if you want one. To stop the browser from opening automatically when a new artifact is published, set `CLAUDE_CODE_ARTIFACT_AUTO_OPEN=0` in your environment. If Claude responds that it cannot publish, or writes a local HTML file without a link, the tool is not enabled for your session. Check the Availability requirements. ## @@ -101,7 +112,7 @@ * You’re running Claude Code v2.1.221 or later. * You’re not in your first session since you installed Claude Code or upgraded from a version before v2.1.221. In that [first session after an install or upgrade](</docs/en/env-vars#first-session-after-an-install-or-upgrade>), Claude might not be able to read comments yet; start a new session and ask again. - * You haven’t turned feature-flag fetching off. If you set `DISABLE_GROWTHBOOK`, `DISABLE_TELEMETRY`, or `DO_NOT_TRACK`, also set [`CLAUDE_CODE_ARTIFACT_COMMENTS=1`](</docs/en/env-vars#features-that-need-feature-flag-fetching>) so Claude can read comments without fetching flags. + * You haven’t turned feature-flag fetching off. ### @@ -109,7 +120,7 @@ Let Claude reply to comments on its own -After your session publishes an artifact, Claude Code watches that artifact for comments for as long as the session runs. When a commenter sends a comment to Claude, it reaches your session right away, and Claude can read the thread and reply without you asking. You need Claude Code v2.1.228 or later. If you turned feature-flag fetching off, also set both [`CLAUDE_CODE_ARTIFACT_COMMENTS=1` and `CLAUDE_CODE_ARTIFACT_COMMENTS_AUTOREACT=1`](</docs/en/env-vars#features-that-need-feature-flag-fetching>). Your [permission mode](</docs/en/permission-modes>) decides what Claude does when a sent comment arrives: +After your session publishes an artifact, Claude Code watches that artifact for comments for as long as the session runs. When a commenter sends a comment to Claude, it reaches your session right away, and Claude can read the thread and reply without you asking. You need Claude Code v2.1.228 or later. If you turned [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>) off, Claude Code doesn’t watch for comments. Your [permission mode](</docs/en/permission-modes>) decides what Claude does when a sent comment arrives: * **Claude replies on its own** : when your permission mode lets Claude post the reply without asking you, Claude reads the thread and replies, and edits the artifact when the comment asks for a change. You see `Auto-replied to comment thread on Artifact: <name>` or `Auto-edited Artifact: <name> in response to a comment thread`. * **Claude waits for you** : outside plan mode, when posting the reply would need your approval, you see `Comments are waiting on Artifact: <name>`. Claude then asks you for approval to read the thread, and again to post the reply. @@ -243,7 +254,7 @@ Constraint| Effect ---|--- -External requests| Apart from Google Fonts and connector data, nothing reaches the page from outside. The CSP blocks scripts, stylesheets, fonts, and images from other hosts, along with `fetch`, XHR, and WebSocket calls, so Claude inlines CSS and JavaScript and embeds images as data URIs. Google Fonts stylesheets load through a `<link>` tag or a CSS `@import` from `fonts.googleapis.com`, along with the font files they reference from `fonts.gstatic.com`. Connector calls go through claude.ai, which makes the network call itself. +External requests| The page can load typefaces from Google Fonts, and scripts from four public CDN hosts: cdnjs, the Tailwind and jQuery CDNs, and selected paths on jsDelivr such as `/npm/`. The CSP blocks every external image and all other external scripts, stylesheets, and fonts, and lets `fetch`, XHR, and WebSocket calls reach only the page’s own origin and the Google Fonts hosts. Claude therefore loads any library the page needs from one of those CDNs, inlines all other CSS and JavaScript, and embeds images as data URIs. Connector calls go through claude.ai, which makes the network call itself. No backend| An artifact is a static page. It can’t store data submitted through a form or authenticate viewers itself. Its only way to fetch data when someone views it is calling MCP connectors, not an API of its own. Single page| Relative links do not resolve, because nothing is deployed alongside the page. For multi-section content, Claude uses in-page anchors rather than separate files. Source file types| The published file must be `.html`, `.htm`, or `.md`. Markdown files render as styled HTML. @@ -279,12 +290,15 @@ To turn artifacts off for your own sessions regardless of your organization’s setting, use any of: -Method| Setting +Where| What to do ---|--- -[Settings file](</docs/en/settings>)| `"disableArtifact": true` -[Environment variable](</docs/en/env-vars>)| `CLAUDE_CODE_DISABLE_ARTIFACT=1` +[`/config`](</docs/en/commands>)| Turn the **Artifacts** row off, which writes [`"enableArtifact": false`](</docs/en/settings-reference#enableartifact>) to your user settings +[Settings file](</docs/en/settings>)| Set `"enableArtifact": false`. The deprecated `"disableArtifact": true` also turns artifacts off +[Environment variable](</docs/en/env-vars>)| Set `CLAUDE_CODE_DISABLE_ARTIFACT=1` [Permission rule](</docs/en/permissions>)| Add `Artifact` to `permissions.deny` +Once you turn artifacts off in a [`--settings`](</docs/en/cli-reference#cli-flags>) file or with `CLAUDE_CODE_DISABLE_ARTIFACT`, or your administrator turns them off in [managed settings](</docs/en/server-managed-settings>), no settings file turns them back on. Before v2.1.242, a file higher in the [precedence stack](</docs/en/settings#settings-precedence>) could turn artifacts back on even when a lower-precedence file set `"enableArtifact": false`. You can also set `"enableArtifact": false` in a project’s `.claude/settings.json` or `.claude/settings.local.json` to turn artifacts off for sessions in that project. An `"enableArtifact": true` in either file doesn’t turn them back on. Honoring the key in project and local settings requires Claude Code v2.1.242 or later. + ## ​ @@ -339,7 +353,7 @@ Allowlist the viewer domain -The viewer on claude.ai loads each artifact from a sandboxed `*.claudeusercontent.com` origin. If your organization restricts outbound network access, add that domain to your allowlist alongside `claude.ai`. See [Network access requirements](</docs/en/network-config#network-access-requirements>) for the full list. An artifact that loads a typeface from Google Fonts also requests `fonts.googleapis.com` and `fonts.gstatic.com`. Both hosts are optional. If you block them, artifacts render in fallback typefaces. Block with a fast rejection rather than a silent drop so the font request fails immediately instead of delaying the page’s first render. +The viewer on claude.ai loads each artifact from a sandboxed `*.claudeusercontent.com` origin. If your organization restricts outbound network access, add that domain to your allowlist alongside `claude.ai`. See [Network access requirements](</docs/en/network-config#network-access-requirements>) for the full list. An artifact that loads a typeface from Google Fonts also requests `fonts.googleapis.com` and `fonts.gstatic.com`. Both hosts are optional. If you block them, artifacts render in fallback typefaces. Block with a fast rejection rather than a silent drop so the font request fails immediately instead of delaying the page’s first render. Artifacts can also load JavaScript libraries, such as React or a charting package, from `cdnjs.cloudflare.com`, `cdn.jsdelivr.net`, `cdn.tailwindcss.com`, and `code.jquery.com`, and from no other external host. If you block those hosts, the parts of an artifact that depend on a library don’t work, and unlike a blocked font, a blocked library has no fallback. Block with a fast rejection here too, so a blocked library request fails at once rather than hanging until it times out. ###
modified Configure auto mode View current →
--- a/auto-mode-config.md +++ b/auto-mode-config.md @@ -336,7 +336,7 @@ Fix a denial with an allow rule, an environment entry, or a retry -Claude Code shows the blocked tool call wherever the denial appears, including the transcript and the **Recently denied** tab. Pick the fix from what the call was trying to reach or do: +To see what the classifier blocked, find the tool call in the conversation. If the call appears shortened or folded into a summary line such as `Ran 3 shell commands`, press `Ctrl+O` to open the [transcript viewer](</docs/en/interactive-mode#transcript-viewer>), which expands it. Two other places on screen that report denials leave out the command or URL: the notice near the input box, such as `bash denied by auto mode · Blocked by classifier · /permissions`, gives the tool and the reason, and the **Recently denied** tab lists a shell command by the description Claude wrote for it. To capture the exact input of these denials programmatically, add a [`PermissionDenied` hook](</docs/en/hooks#permissiondenied>), which receives it as `tool_input`. The text beneath the call tells you whether there is anything to fix. Text that reports a problem with the classifier itself, such as a model that `is temporarily unavailable` or a classifier error, means Claude Code blocked the call without a final verdict from the classifier; see [Auto mode cannot determine the safety of an action](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>) for what to do. Otherwise, a line reading `Denied by auto mode classifier` with a reason such as `Blocked by classifier` means the classifier judged the call unsafe, so pick the fix from what the call was trying to reach or do: * A destination Claude needs throughout the task, such as a package registry, an internal domain, or a repository host: add it to `autoMode.environment`. * A command you want to run without review from now on: add an `allow` rule.
modified Best practices for Claude Code View current →
--- a/best-practices.md +++ b/best-practices.md @@ -464,9 +464,10 @@ Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows. -Pick the parallel approach that fits how much coordination you want to do yourself: +Pick the parallel approach that fits how much coordination you want to do yourself, and add messaging when the sessions need to pass findings between them: * [Worktrees](</docs/en/worktrees>): run separate CLI sessions in isolated git checkouts so edits don’t collide + * [Cross-session messaging](</docs/en/cross-session-messaging>): let the sessions you run yourself pass findings to each other * [Desktop app](</docs/en/desktop#work-in-parallel-with-sessions>): manage multiple local sessions visually, each in its own worktree * [Claude Code on the web](</docs/en/claude-code-on-the-web>): run sessions in the cloud, on Anthropic-managed infrastructure by default * [Agent view](</docs/en/agent-view>): research preview. Run `claude agents` to dispatch sessions that keep running in the background and watch them from one screen
modified Claude Code changelog View current →
Show diff (149 lines)
--- a/changelog.md +++ b/changelog.md @@ -1,4 +1,146 @@ This page is generated from the [CHANGELOG.md on GitHub](<https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md>). Run `claude --version` to check your installed version. + +​ + +2.1.251 + +August 28, 2026 + + * Added `PreModelSwitch` and `PostModelSwitch` hook events (block, confirm, or annotate a model switch); `SessionStart` resume hooks now receive session staleness and the estimated re-cache cost + * Added live streaming of a foreground subagent’s tool calls and results to Remote Control clients (background subagents, the default, still show status only) + * Added a Spend limit bar to `/usage` and a `rate_limits.spend_limit` status line field for developers behind a Claude apps gateway with spend limits + * Added a per-session prompt-cache line to `/cost` (hit ratio, misses, tokens re-cached, warm/cold) and a matching `prompt_cache` object for status line scripts + * Added `attach`, `logs`, `stop`, `respawn`, and `rm` to `claude --help`; the `--resume` message for a running background session now names the exact `claude attach <id>` command + * Fixed file tools (Read, Write, Edit) following a symlink swapped inside the working directory after the permission check, which could read or write outside the approved location + * Fixed plugin commands declared in a marketplace entry being able to point outside the plugin directory; such paths are now rejected with a path-traversal error + * Fixed project settings being able to enable detailed beta tracing or raw API body logging, and a lower-scope beta tracing endpoint bypassing an OTLP collector pinned by managed settings or a host app + * Fixed the Workflow tool reading (and quoting in errors) a `scriptPath` outside what the session may read before the permission check ran + * Fixed Grep and Glob not applying `Read(...)` deny rules to files reached through a symlinked search path + * Fixed conversations getting stuck on “text content blocks must be non-empty” errors after a turn where the model produced only thinking + * Fixed the first launch on a fresh install starting in default mode instead of auto mode for accounts whose startup default is auto mode + * Fixed Opus 5 requests failing with “effort … is not supported when thinking is disabled” when effort was xhigh/max and thinking was turned off; effort is now sent as `high` in that case + * Fixed replying to a message Claude Desktop delivered from another session: `SendMessage` to that session id now delivers through Claude Desktop instead of failing with “not reachable” + * Fixed TUI lag with many parallel subagents: per-second progress ticks now replace their predecessor instead of piling up in the transcript + * Fixed agent teams: a teammate’s final answer not reaching the team lead — it now arrives in the idle notification instead of a content-free “available” notice + * Fixed background subagents being unable to reply to a message from an unnamed sibling or parent agent (`from` was the agent type, which is not an address) + * Fixed managed-settings `disableAutoMode` arriving mid-session not moving an already-running auto-mode session back to default mode + * Fixed a “switch to Opus 1M for 5x more context” tip that appeared even when the current Opus model already has a 1M context window + * Fixed Claude apps gateway sessions treating a stored Anthropic profile (e.g. a Console sign-in) as active: listing it in `/status` and retrying gateway 401s with it, though requests never use it + * Fixed cloud sessions telling Claude the model had changed when the host was only setting the session’s initial model + * Fixed Remote Control reporting a failure when an organization’s policy disables it; it now shows a single quiet notice instead + * Fixed `/mcp reconnect` on Remote Control showing a generic withheld-detail error instead of the real remedy when a server was disabled in another session + * Fixed `--input-format stream-json`: client-injected assistant tool calls sent without a message id were merged into the first one and their results lost, including when resuming older sessions + * Fixed session transcripts being silently overwritten when a directory change relocated a session onto an existing same-ID transcript + * Fixed background sessions and their subagents being unable to edit files inside a git worktree they created with `git worktree add` + * Fixed background sessions occasionally starting without any plugin skills (and staying that way) when another Claude Code process was refreshing the plugin marketplace at the same moment + * Fixed selecting text in an opened background session inside tmux over SSH: it now copies to the tmux buffer like a foreground session instead of falling back to OSC 52 + * Fixed SDK and cloud sessions hanging indefinitely when an SDK MCP server’s handshake acknowledgment was lost; the wait now times out after 70 seconds and marks only that server failed + * Fixed self-hosted runner leaving a stuck session’s Bash tool processes running after the session was force-stopped + * Fixed `/usage-credits` for Team and Enterprise members whose admin set the org’s usage-credit limit to $0: it now offers to ask the admin instead of saying a cap was reached + * Fixed `--worktree --tmux` with a merge-request number on a gitlab.com origin trying a doomed GitHub-style fetch first instead of fetching the GitLab ref directly + * Fixed Ctrl+G failing with “Emacs quit unexpectedly” in background sessions for editors that open `/dev/tty`, such as `emacs -nw` and `micro` + * Fixed an `additionalDirectories` entry containing a null byte crashing startup, or breaking `/add-dir` and later settings updates when it came from an SDK host, IDE, or hook; it is now skipped + * Fixed the MCP server menu’s copy shortcut: it now says how the sign-in URL was copied instead of always claiming success + * Fixed italic text (such as the session recap line) rendering as highlighted blocks in GNU screen and in tmux sessions using a `screen` terminal type + * Fixed `claude mcp add --header` and `claude mcp add-json` help text naming the wrong transports + * Fixed `claude ultrareview` and `/ultrareview` waiting the full 30 minutes when the cloud session fails to start; they now stop early and report the reason + * Fixed Bash permission checks auto-approving commands that assign an arithmetic expression to an integer shell variable (e.g. `OPTIND=1/0`, `RANDOM=2+2`); these now prompt for approval + * Fixed backgrounded sessions (`←`, `/background`, `--bg`) losing a Vertex/Bedrock gateway (`ANTHROPIC_*_BASE_URL` \+ `CLAUDE_CODE_SKIP_*_AUTH`) exported in the shell, so every request failed + * Fixed `claude --bg --model fable` on Max plans stopping to ask for usage credits while the interactive session on the same account still had Fable allowance + * Fixed the one-time “make auto mode your default” offer appearing in unattended sessions (e.g. agent-team teammate panes), where a stray keypress could accept it unread + * Fixed the managed-settings approval prompt re-appearing after signing in again to the same Claude apps gateway when the settings are unchanged + * Fixed disabled `/bug` and `/share` reporting that `/feedback` was disabled; tips, `/help`, and refusal messages no longer suggest `/feedback` when an org policy or env var turns it off + * Fixed cloud session creation advising GitHub setup after a transient GitHub connection failure — the message now says to retry instead + * Improved CPU usage during turns in interactive sessions by cutting redundant UI re-renders + * Improved install size: the native binary is about 5 MB smaller + * Improved cloud sessions: when the session’s network proxy drops a connection during a Bash command, the tool result now names the host and reason instead of only “connection reset” + * Improved `/schedule` to explain that MCP servers configured in Claude Code can’t be attached to cloud routines, instead of a bare “No MCP connectors” message + * Improved framing of messages from your own subagents: Claude is told the sender is a worker inside this session, not an unrelated Claude session + * Improved the prompt placeholder to read “Message @name…” while viewing a background subagent or fork transcript opened from the subagent panel or `/tasks` + * Improved sanitization of MCP server names in error messages, menus, and command results + * Improved Amazon Bedrock session start under `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` (e.g. Claude Desktop): a session given a Bedrock model ID or ARN no longer waits for inference-profile discovery + * Improved the managed settings approval dialog to list only the settings that changed since you last approved them + * Improved retry when the model’s tool call is malformed: the broken output is now dropped from the retry context, including on Bedrock, Vertex, and Foundry + * Changed `/radio` to be available on Bedrock, Vertex AI, Foundry, and Claude Platform on AWS, and when telemetry is disabled + * Changed Claude in Chrome so browser actions always go through Claude Code’s permission checks, including in sessions with telemetry disabled, which previously used the Chrome extension’s own prompts + * Changed `CLAUDE_CODE_SUBAGENT_MODEL` to set the default subagent model rather than override everything: an agent definition’s `model:` and an explicit per-spawn model now take precedence over it + * Changed the default commit trailer to `Co-Authored-By: Claude Code` when the active model isn’t a recognized Claude model (e.g. third-party models behind a custom `ANTHROPIC_BASE_URL`) + * Changed the default model for seat-based Enterprise subscriptions to Opus 5, matching other premium plans + * Changed `/effort` to save your default effort level per model, so each model keeps its own setting when you switch + * Changed analytics to no longer turn off before sign-in solely because managed settings force gateway login (or cannot be read); they stay off once signed in to the gateway or via `DISABLE_TELEMETRY` + * Changed the footer PR badge on Bedrock, Vertex, and Foundry, and when telemetry is off, to call the GitHub API directly (via `gh auth token`, `GH_TOKEN`, or `GITHUB_TOKEN`) instead of `gh pr view` + * Changed how Bash command output files are created and read back when commands run in the sandbox, so a sandboxed command cannot redirect or replace them + * Changed plugin/LSP install suggestions and the auto-mode default offer to wait until you’ve sent or cleared what you’re typing, so the Enter that sends your prompt can’t answer them + * Changed server-managed settings that terminate sandbox TLS, route sandbox traffic through your own proxy, inject credentials, or weaken sandbox isolation to require approval before they apply + * Changed `ANTHROPIC_CUSTOM_HEADERS` from managed or project settings to require approval when it sets a credential, org/tenant, routing, or API-behavior header (e.g. `Authorization`, `Host`) + * Changed project-level `.claude/settings.json` `env` to no longer set `CLAUDE_CONFIG_DIR`, `CLAUDE_CODE_TMPDIR`, or `TMPDIR`/`TMP`/`TEMP`; set them in your shell, user, or managed settings instead + * Removed syntax highlighting for six rarely used languages (1c, gml, isbl, mathematica, maxima, sqf); the binary is 2.5 MB smaller + * [VSCode] Fixed the sign-in screen’s “Bedrock, Foundry, or Vertex” button opening the docs at the top of the page instead of the third-party provider setup section + * [VSCode] Changed the Remote Control banner to a footer pill (shown while Remote Control is on or has failed) that opens the session on claude.ai/code; turn it on or off with `/remote-control` + +​ + +2.1.250 + +August 28, 2026 + + * Bug fixes and reliability improvements + +​ + +2.1.248 + +August 27, 2026 + + * Added `--restricted` (or `CLAUDE_CODE_RESTRICTED=1`): removes the built-in tools that run commands or code and `WebFetch` (unless named in `--tools`), keeps file tools inside the working directory, refuses `bypassPermissions`, and ignores user, project and local settings files + * Added `experimental.cacheTtl` (`"5m"` or `"1h"`) to agent frontmatter: a per-agent prompt cache TTL used when no subagent TTL setting is configured + * Added `claude self-hosted-runner --client-label <label>` (or `SELF_HOSTED_RUNNER_CLIENT_LABEL`) to override the label the runner registers with (default: hostname) + * Added server-managed settings diagnostics: a startup warning when the settings fail to load, and a `/doctor` and `/status` line explaining a load failure or why they weren’t fetched (Bedrock/Vertex/third-party provider, custom `ANTHROPIC_BASE_URL`) + * Added a warning in `/web-setup` when the GitHub CLI token lacks the `workflow` scope, since pushes to very large repositories can be rejected without it + * Added `/usage-credits` for Enterprise organizations billed through AWS Marketplace, self-serve Enterprise, and Enterprise trials, so members can request a higher usage limit from their admin + * Added cross-session messaging (`SendMessage` / `ListAgents`) between sessions on the same machine on Bedrock, Vertex, and Foundry, and when telemetry is disabled + * Fixed a prompt-cache miss (and lost extended-thinking context) roughly once an hour in long sessions, caused by tool definitions being re-rendered after an OAuth token refresh + * Fixed the `ScheduleWakeup` tool definition changing between a session and its `--resume` when the account had entered usage overage, causing a full prompt-cache miss on the resumed session’s first turn + * Fixed Claude Desktop and Cowork sessions disappearing after 30 days: the transcript cleanup now keeps desktop-written sessions while they are in the app (unless org policy manages retention); the new `desktopSessionCleanupPeriodDays` setting caps the exemption + * Fixed being sent to the login screen when another Claude Code process held the token refresh lock while the session token had expired; the request now fails with a retryable error instead + * Windows: Fixed the `claude agents` list not responding to the keyboard after detaching from a session, or when launched in a terminal tab left in win32-input-mode + * Fixed the recommended Console sign-in in `/login` failing with an OAuth error before showing a sign-in URL on machines where it can’t be used (for example when `ANTHROPIC_API_KEY` or an API key helper is set); it now falls back to the API-key sign-in + * Fixed model names in `/model` and fast-mode switch notices to render as code, so suffixes like `[1m]` display literally instead of as a link + * Fixed `claude agents` skipping the workspace trust prompt when the `CI` environment variable is set + * Fixed `claude agents` crashing on launch when the PR-status cache held a malformed entry + * Fixed agent view resurrecting a weeks-old background session after the machine was off: such a session now shows as stopped at its real end, and opening it asks before resuming its saved conversation + * Fixed agent view sometimes opening an older conversation, and dropping the typed prompt, when starting a new session + * Fixed `claude agents`: opening a stopped session that you already resumed in another terminal no longer starts a second process on that conversation; the row now says it is open in a terminal + * Fixed `claude agents` and `claude rm` refusing to delete a session (“has commits that are not pushed anywhere”) when its worktree branch was already merged into your checked-out default branch (e.g. local `main`) but not yet pushed + * Fixed background sessions waiting silently when a `PermissionRequest` or `PreToolUse` hook prints an invalid answer: the `claude agents` row now names the hook and the schema error + * Fixed hooks silently treating a stdout `{…}` object that isn’t valid JSON as plain text; it’s now reported as a hook error with the parse message + * Fixed `/mcp` listing a project `.mcp.json` entry that declares the claude.ai connector type under the trusted “claude.ai” heading; it now appears under its real scope + * Fixed MCP servers whose `headersHelper` supplies the `Authorization` header falling into OAuth discovery on a 401 instead of re-running the helper and retrying the call as documented + * Fixed `/login` to a Claude apps gateway hanging when the managed-settings security approval dialog was required + * Fixed gateway model discovery (`CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY`) never running when `apiKeyHelper` is the only credential + * Fixed `claude logs` leaving mouse tracking, bracketed paste and the alternate screen switched on in the terminal it was run from + * Fixed the trust dialog’s list of repo permission rules showing a garbled character when a long rule was cut off in the middle of an emoji + * Fixed the permission mode indicator staying hidden behind the “Press Ctrl-C again to exit” hint when you press shift+tab right after ctrl+c + * Fixed `/ultrareview` and locally seeded cloud sessions uploading uncommitted edits to `prod.env`-style and `*.tfvars` files, or to editor swap, temp, and backup copies of credential files (e.g. `key.pem.tmp`, `id_rsa.swo`); they now stay on your machine + * Fixed Remote Control sessions occasionally never showing a permission prompt or the latest messages on the connected device after the CLI silently reconnected + * Fixed cloud sessions occasionally failing at startup when the container’s session credentials were not yet readable + * Fixed `claude remote-control` rejecting its own flags (e.g. `--spawn`, `--name`) when a global flag or a wrapper-injected option precedes the subcommand + * Fixed startup warnings (e.g. “N MCP servers need authentication”) rendering one column right of the rest of the transcript + * Fixed a backgrounded worktree session losing its checkout: the background session now holds the worktree’s lock while it runs, so cleanup and `git worktree remove` leave it alone + * Fixed @-mentions of other sessions not matching names typed with non-Latin characters (for example Korean entered through an IME) + * Fixed an invalid `crossSessionInbound` value being silently ignored: it now warns and holds cross-session messages (user settings) or refuses them (managed settings) until fixed + * Fixed rate-limit, usage, and fast-mode messages telling you to run `/usage-credits` when that command isn’t available for your organization (e.g. hidden with `DISABLE_EXTRA_USAGE_COMMAND`) + * [VSCode] Fixed a chat tab getting stuck on “No conversation found” when its session was never saved; it now starts a new conversation instead + * Improved the Workflow tool’s prompt footprint: its description is now about 1k tokens instead of 5.7k, with the script-writing reference moved into a bundled `workflow-authoring` skill + * Improved the prompt-footer PR badge to check GitHub less often while the pull request is unchanged; a push or a `gh pr` command still refreshes it right away + * Improved managed settings: client-side timeout, MCP startup-mode, and stream-watchdog env vars no longer trigger the settings-approval prompt + * Improved `/ultrareview <PR#>` to check before launch that the GitHub account connected to your Claude account can access the repository, and to explain how to fix it, instead of failing after the cloud session starts + * Improved cross-session messaging: falls back to a private per-user `/tmp` directory when the default one can’t be used, and the notice and `/status` name the directory to fix + * Changed shift+enter in the agent view dispatch input to insert a newline (matching the prompt); ctrl+enter now dispatches and attaches + * Changed `/loop`: self-paced dynamic mode and the no-prompt autonomous default are now always available, including on Bedrock/Vertex/Foundry + * Changed Anthropic telemetry export failures to log at debug level as `[Anthropic telemetry]` instead of `[3P telemetry] OTEL diag error`, so they are not mistaken for your OTel collector failing + * Changed cross-session messaging in Linux user namespaces: root-equivalent trust for unmapped owners is limited to canonical system directories + * Changed `SendMessage` from a subagent to another session: the result now notes that any reply is delivered to the parent session’s conversation, not to the subagent ​
modified Channels reference View current →
--- a/channels-reference.md +++ b/channels-reference.md @@ -73,7 +73,7 @@ { // this key is what makes it a channel — Claude Code registers a listener for it capabilities: { experimental: { 'claude/channel': {} } }, - // added to Claude's system prompt so it knows how to handle these events + // Claude Code delivers this to Claude as context when the server connects, so it knows how to handle these events instructions: 'Events from the webhook channel arrive as <channel source="webhook" ...>. They are one-way: read them and act, no reply expected.', }, ) @@ -102,7 +102,7 @@ The file does three things in order: - * **Server configuration** : creates the MCP server with `claude/channel` in its capabilities, which is what tells Claude Code this is a channel. The `instructions` string goes into Claude’s system prompt: tell Claude what events to expect, whether to reply, and how to route replies if it should. + * **Server configuration** : creates the MCP server with `claude/channel` in its capabilities, which is what tells Claude Code this is a channel. Claude Code delivers the `instructions` string to Claude as context when the server connects: tell Claude what events to expect, whether to reply, and how to route replies if it should. * **Stdio connection** : connects to Claude Code over stdin/stdout. This is standard for any [MCP server](<https://modelcontextprotocol.io/docs/concepts/transports#standard-io>). * **HTTP listener** : starts a local web server on port 8788. Every POST body gets forwarded to Claude as a channel event via `mcp.notification()`. The `content` becomes the event body, and each `meta` entry becomes an attribute on the `<channel>` tag. The listener needs access to the `mcp` instance, so it runs in the same process. You could split it into separate modules for a larger project. @@ -140,7 +140,7 @@ Your terminal renders the event as a one-line summary, `← webhook: build failed on main: https://ci.example.com/run/1234`, rather than the raw tag. You’ll then see Claude start responding: reading files, running commands, or whatever the message calls for. This is a one-way channel, so Claude acts in your session but doesn’t send anything back through the webhook. To add replies, see Expose a reply tool.If the event doesn’t arrive, the diagnosis depends on what `curl` returned: - * **`curl` succeeds but nothing reaches Claude**: run `/mcp` in your session to check the server’s status. “Failed to connect” usually means a dependency or import error in your server file; check the debug log at `~/.claude/debug/<session-id>.txt` for the stderr trace. + * **`curl` succeeds but nothing reaches Claude**: run `/mcp` in your session to check the server’s status. A `failed` status usually means a dependency or import error in your server file; check the debug log at `~/.claude/debug/<session-id>.txt` for the stderr trace. * **`curl` fails with “connection refused”**: the port is either not bound yet or a stale process from an earlier run is holding it. `lsof -i :<port>` shows what’s listening; `kill` the stale process before restarting your session. The [fakechat server](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/fakechat>) extends this pattern with a web UI, file attachments, and a reply tool for two-way chat. @@ -176,7 +176,7 @@ `capabilities.experimental['claude/channel']`| `object`| Required. Always `{}`. Presence registers the notification listener. `capabilities.experimental['claude/channel/permission']`| `object` or `false`| Optional. Set it to `{}` to declare that this channel can receive permission relay requests. When declared, Claude Code forwards tool approval prompts to your channel so you can approve or deny them remotely. To opt out, omit the key or set it to `false`. Before v2.1.234, Claude Code treated `false` as declared. See Relay permission prompts. `capabilities.tools`| `object`| Two-way only. Always `{}`. Standard MCP tool capability. See Expose a reply tool. -`instructions`| `string`| Recommended. Added to Claude’s system prompt. Tell Claude what events to expect, what the `<channel>` tag attributes mean, whether to reply, and if so which tool to use and which attribute to pass back (like `chat_id`). +`instructions`| `string`| Recommended. Claude Code delivers it to Claude as context when the server connects. Tell Claude what events to expect, what the `<channel>` tag attributes mean, whether to reply, and if so which tool to use and which attribute to pass back (like `chat_id`). To create a one-way channel, omit `capabilities.tools`. This example shows a two-way setup with the channel capability, tools, and instructions set: @@ -189,7 +189,7 @@ experimental: { 'claude/channel': {} }, // registers the channel listener tools: {}, // omit for one-way channels }, - // added to Claude's system prompt so it knows how to handle your events + // Claude Code delivers this to Claude as context when the server connects, so it knows how to handle your events instructions: 'Messages arrive as <channel source="your-channel" ...>. Reply with the reply tool.', }, )
modified Use Claude Code with Chrome View current →
--- a/chrome.md +++ b/chrome.md @@ -66,7 +66,7 @@ If Claude Code asks for permission before a browser action, approve it. The dialog starts with `Claude in Chrome wants to` and offers an option to allow all actions on that site for the session. Claude opens a new tab and starts the task. -Run `/chrome` at any time to check the connection status, manage permissions, reconnect the extension, or choose which connected browser to use. The integration is working when the status panel shows “Status: Enabled” and “Extension: Installed”. If more than one browser is connected, you choose which one Claude uses. When a browser action starts before you’ve chosen, Claude prompts you to pick one. To switch browsers later, run `/chrome` and select **Select browser…**. Claude keeps using your choice even when another browser connects. Browser selection requires Claude Code v2.1.154 or later. For VS Code, see [browser automation in VS Code](</docs/en/vs-code#automate-browser-tasks-with-chrome>). +Run `/chrome` at any time to check the connection status, manage permissions, reconnect the extension, or choose which connected browser to use. The integration is working when the status panel shows “Status: Enabled” and “Extension: Installed”. If more than one browser is connected, you choose which one Claude uses. When a browser action starts before you’ve chosen, Claude prompts you to pick one. To switch browsers later, run `/chrome` and select **Select browser…**. Claude keeps using your choice even when another browser connects. For VS Code, see [browser automation in VS Code](</docs/en/vs-code#automate-browser-tasks-with-chrome>). ###
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 @@ -335,7 +335,7 @@ Lock behavior across sources -Setting one lock doesn’t restrict the others; each key is documented in the [settings reference](</docs/en/settings-reference#all-settings>). From an admin source below the winner, the two sandbox locks still apply, and `allowManagedPermissionRulesOnly` still blocks parent-supplied allow rules and `additionalDirectories`. The hooks and MCP server locks, and `allowManagedPermissionRulesOnly`’s effect on the developer’s own rules, need the winning source. On [`policyHelper`](</docs/en/settings-reference#policyhelper>) fleets, the locks are read from the helper’s output alone. Each lock makes Claude Code ignore the developer’s own entries for that setting, so include your organization’s allowlists next to the locks. Locking network domains with an empty managed domain list blocks all sandboxed outbound traffic, and locking MCP servers with no managed or parent-supplied `allowedMcpServers` loads every server that `deniedMcpServers` doesn’t block. `allowRead` entries only re-allow paths inside `denyRead` regions, so pair them with a managed `denyRead`. +Setting one lock doesn’t restrict the others; each key is documented in the [settings reference](</docs/en/settings-reference#all-settings>). From an admin source below the winner, the two sandbox locks still apply, and `allowManagedPermissionRulesOnly` still blocks parent-supplied allow rules and `additionalDirectories`. The hooks and MCP server locks, and `allowManagedPermissionRulesOnly`’s effect on the developer’s own rules, need the winning source by default; under the `managedSourcesBehavior` merge opt-in in [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>), Claude Code applies the strictest value any source sets for every lock. On [`policyHelper`](</docs/en/settings-reference#policyhelper>) fleets, the locks are read from the helper’s output alone. Each lock makes Claude Code ignore the developer’s own entries for that setting, so include your organization’s allowlists next to the locks. Locking network domains with an empty managed domain list blocks all sandboxed outbound traffic, and locking MCP servers with no managed or parent-supplied `allowedMcpServers` loads every server that `deniedMcpServers` doesn’t block. `allowRead` entries only re-allow paths inside `denyRead` regions, so pair them with a managed `denyRead`. #### @@ -343,7 +343,7 @@ Settings the locks don’t cover -Four parent-supplied settings are honored even with all five locks set: +Four parent-supplied settings pass the filter even with all five locks set. Under the default first-wins setting, the admin value that blocks the parent’s is the one in the highest-priority admin source. Under the `managedSourcesBehavior` merge opt-in, [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) says which source’s value applies instead. * **`forceLoginOrgUUID`** : Claude Code honors a parent-supplied value when the highest-priority admin source doesn’t set an org UUID. Gateway sign-in doesn’t check this key, so it matters only for fleets that also use first-party Anthropic logins. An org UUID in the highest-priority admin source blocks the parent’s value and is the one Claude Code enforces, so set `forceLoginOrgUUID` there. * **`allowedMcpServers`** : Claude Code honors a parent-supplied allowlist when the highest-priority admin source doesn’t set one, and `allowManagedMcpServersOnly` doesn’t block it, because the lock enforces whichever list wins as the managed value, including a parent-supplied list when the highest-priority admin source doesn’t set one. A list in the highest-priority admin source blocks the parent’s and is the list Claude Code enforces, so set `allowedMcpServers` there, next to the lock. Before v2.1.223, a value for either key in any admin source blocked the parent’s. @@ -377,7 +377,7 @@ * **Model access** : requests for models the policy doesn’t grant return 400, and the `/model` picker is filtered to the policy’s `availableModels` allowlist. Set [`enforceAvailableModels: true`](</docs/en/model-config#default-model-behavior>) in the policy so the Default option resolves to a model inside `availableModels` instead of to Claude Code’s built-in default; without it, Default stays selectable and is rejected at request time if that model isn’t granted. * **Telemetry destination** : in sessions signed in through `/login`, the CLI sends its OTLP/HTTP exports to the gateway regardless of any locally set `OTEL_EXPORTER_OTLP_ENDPOINT`, and the gateway relays them to the destinations in [`telemetry.forward_to`](</docs/en/claude-apps-gateway-config#telemetry>). In the embedded sessions Claude Desktop launches, the CLI sends its exports to the configured `OTEL_EXPORTER_OTLP_ENDPOINT`. The CLI attaches the gateway session token to those exports only when that endpoint points at the gateway itself. With no destination configured for a signal, the gateway accepts and discards it, so if you already collect Claude Code telemetry directly, add your collector as a `forward_to` destination. * **Credentials** : the gateway token is the session’s only credential. `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_API_KEY`, `apiKeyHelper`, [Anthropic profiles](</docs/en/authentication#anthropic-profiles-and-federation-credentials>), and any earlier claude.ai login are ignored while signed in, so developers don’t need to log out of claude.ai first. - * **Managed settings** : locked keys can’t be overridden locally. The CLI applies the policy at startup and on each hourly poll. + * **Managed settings** : locked keys can’t be overridden locally. The CLI applies the policy at startup and applies changes on each hourly poll, apart from the [changes that apply only at the next launch](</docs/en/server-managed-settings#fetch-and-caching-behavior>). * **Startup** : signed-in sessions exit at startup with an error after about 10 seconds when the gateway is unreachable, rather than starting without their settings. * **Deprovisioning** : a session whose user is disabled in the IdP expires within `ttl_hours` when the next refresh fails.
modified Claude apps gateway configuration View current →
--- a/claude-apps-gateway-config.md +++ b/claude-apps-gateway-config.md @@ -531,7 +531,7 @@ The gateway keeps no user directory of its own. It authorizes each request from the user’s IdP token, reading group membership from the token’s `groups` claim and evaluating policies against it. There is no roster to enumerate and no accounts to pre-create, and therefore no SCIM endpoint, because there is nothing for SCIM to sync into.Run user and group lifecycle management at the source of truth, which is your IdP’s native SCIM provisioning or a dedicated identity-governance platform. Membership and deprovisioning governed there flow into the gateway automatically through the token. If you want SCIM provisioning of Claude accounts themselves, that is a [Claude for Enterprise](</docs/en/admin-setup>) capability.Two propagation clocks apply: - * **Policy contents** : editing a policy and redeploying reaches connected clients on their next managed-settings poll, within an hour + * **Policy contents** : editing a policy and redeploying reaches connected clients on their next managed-settings poll, within an hour, apart from the [changes that apply only at the next launch](</docs/en/server-managed-settings#fetch-and-caching-behavior>) * **Group membership** : changing a user’s group membership changes which policy matches them. This takes effect on the next session re-mint, meaning the next silent refresh, bounded by `session.ttl_hours`. #### @@ -660,7 +660,7 @@ Precedence with other managed sources -If a device also has an MDM-delivered policy or a local `managed-settings.json`, Claude Code doesn’t merge the managed sources: gateway-delivered settings rank first, so the local sources supply the policy only when the gateway delivers no policy key. [Precedence within the managed tier](</docs/en/managed-settings#precedence-within-the-managed-tier>) on the managed settings page has the full ranking and the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>) regardless of which source it selected, such as the sandbox lock keys, `forceRemoteSettingsRefresh`, and the per-variable `env` merge. A [`policyHelper`](</docs/en/settings-reference#policyhelper>) configured in an MDM profile or the managed settings file runs only when the gateway delivers no settings; the entry says what its output replaces. Embedding hosts such as [Claude Desktop](</docs/en/desktop>) can supply policy through the SDK `managedSettings` option. [Parent settings from embedding hosts](</docs/en/managed-settings#parent-settings-from-embedding-hosts>) says when Claude Code applies it, and [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>) lists which allow-direction settings still apply without the `allowManaged*Only` locks. 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. +If a device also has an MDM-delivered policy or a local `managed-settings.json`, gateway-delivered settings rank first. [Precedence within the managed tier](</docs/en/managed-settings#precedence-within-the-managed-tier>) on the managed settings page says when the local sources apply, and has the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>) regardless of which source it selected, such as the sandbox lock keys, `forceRemoteSettingsRefresh`, and the per-variable `env` merge. A [`policyHelper`](</docs/en/settings-reference#policyhelper>) configured in an MDM profile or the managed settings file runs only when the gateway delivers no settings; the entry says what its output replaces. Embedding hosts such as [Claude Desktop](</docs/en/desktop>) can supply policy through the SDK `managedSettings` option. [Parent settings from embedding hosts](</docs/en/managed-settings#parent-settings-from-embedding-hosts>) says when Claude Code applies it, and [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>) lists which allow-direction settings still apply without the `allowManaged*Only` locks. 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. At boot, the gateway rejects `mcpServers` inside a policy’s `cli` block. You can’t distribute MCP servers per group to Claude Code clients; deploy MCP servers via the file-based `managed-mcp.json` on each device or let developers add them locally. You can deliver Claude Desktop’s `managedMcpServers` setting to Claude Desktop clients through a policy’s `desktop` block. To set it, you need Claude Code v2.1.232 or later on the gateway server. @@ -896,7 +896,7 @@ Linux and WSL| `/etc/claude-code/managed-settings.json` Windows| `C:\Program Files\ClaudeCode\managed-settings.json`, or Group Policy via the HKLM registry -A registry policy on Windows or a managed-preferences plist on macOS replaces the `managed-settings.json` file rather than merging with it, apart from the exception keys and cross-source checks above. All three keys in this snippet follow the highest-priority-source rule, so fleets that deliver policy through Group Policy or configuration profiles must put all three in that mechanism instead. For Claude Desktop, set the `bootstrapUrl` key in Claude Desktop’s own [managed configuration](<https://claude.com/docs/third-party/claude-desktop/configuration>) to `<listen.public_url>/user/bootstrap`. The sign-in flow and per-group policy then match the CLI’s once a policy opts in server-side with a `desktop` key; without the opt-in, `/user/bootstrap` returns 404. See Claude Desktop overlay for the server-side half. [`forceLoginGatewayUrl`](</docs/en/settings-reference#forcelogingatewayurl>), and the `"gateway"` value of [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>), are honored only from a managed source on the machine: `managed-settings.json`, the macOS plist or Windows HKLM registry, or a policy helper. A developer setting them in their own `~/.claude/settings.json` has no effect, and neither does setting them in the gateway payload. +By default, a registry policy on Windows or a managed-preferences plist on macOS replaces the `managed-settings.json` file rather than merging with it, apart from the exception keys and cross-source checks above. All three keys in this snippet follow the highest-priority-source rule, so fleets that deliver policy through Group Policy or configuration profiles must put all three in that mechanism instead. For Claude Desktop, set the `bootstrapUrl` key in Claude Desktop’s own [managed configuration](<https://claude.com/docs/third-party/claude-desktop/configuration>) to `<listen.public_url>/user/bootstrap`. The sign-in flow and per-group policy then match the CLI’s once a policy opts in server-side with a `desktop` key; without the opt-in, `/user/bootstrap` returns 404. See Claude Desktop overlay for the server-side half. [`forceLoginGatewayUrl`](</docs/en/settings-reference#forcelogingatewayurl>), and the `"gateway"` value of [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>), are honored only from a managed source on the machine: `managed-settings.json`, the macOS plist or Windows HKLM registry, or a policy helper. A developer setting them in their own `~/.claude/settings.json` has no effect, and neither does setting them in the gateway payload. ##
modified Claude apps gateway deployment and operations View current →
--- a/claude-apps-gateway-deploy.md +++ b/claude-apps-gateway-deploy.md @@ -246,9 +246,10 @@ * **Data residency** : the gateway’s own data plane sends nothing to Anthropic unless the Anthropic API is a configured upstream; when it is, your existing data-handling agreement applies to the inference path. Telemetry, audit, identity, and settings go only to the destinations you configure. * **Host-process traffic** : the host process is the Claude Code CLI. `claude gateway` runs under the same third-party rules as Amazon Bedrock and Google Cloud’s Agent Platform deployments and sends nothing to Anthropic. Before v2.1.227, the host process sent startup telemetry such as product version and platform, which setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` in the container environment turned off. Those releases also sent one `HEAD` request at boot, with no body or credentials, to `/api/hello` on `https://api.anthropic.com`, or on `ANTHROPIC_BASE_URL` when the environment set it, unless the environment also set a proxy variable such as `HTTPS_PROXY` or an mTLS client certificate. They ignored the response, so blocking that request at the egress firewall didn’t affect the gateway. - * **Client analytics** : the CLI disables its own usage analytics while signed in to a gateway, and error reporting is off by default on third-party API surfaces. + * **Client analytics** : the CLI disables its own usage analytics and error reporting while signed in to a gateway. On machines where a [managed settings file, an MDM profile, or a policy helper](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) sets `forceLoginMethod: "gateway"`, the CLI disables them from startup, before anyone signs in. When an [admin policy source](</docs/en/managed-settings#which-managed-source-claude-code-uses>) fails to load, the CLI turns usage analytics and error reporting off as well, since the unreadable source may be the one that mandates the gateway. Before v2.1.247, the CLI turned analytics off only once a gateway sign-in stored the credential, so the first run on those machines still sent startup events and a feature-flag request to Anthropic. + * **Error reporting** : the CLI turns error reporting off whenever its model requests go to any endpoint other than Anthropic’s first-party API, such as Amazon Bedrock or a custom `ANTHROPIC_BASE_URL`. * **Client machines** : developers’ CLIs still send WebFetch hostname checks and version checks to Anthropic unless `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` and `skipWebFetchPreflight: true` are set. See [data usage](</docs/en/data-usage>). - * **Survey ratings** : the gateway credential disables the Anthropic-bound rating sink, so ratings aren’t sent to Anthropic. + * **Survey ratings** : gateway sign-in, or managed settings that force gateway sign-in, disables the Anthropic-bound rating sink from the same point as the analytics streams, so ratings aren’t sent to Anthropic. * **Transcript sharing** : choosing Yes on a survey’s transcript-share prompt writes a local file under `~/.claude/feedback-bundles/` instead of uploading to Anthropic. * **Client updates** : update checks are separate from gateway traffic. Pin versions through your own distribution and set `DISABLE_UPDATES` if laptops must not fetch releases. `DISABLE_AUTOUPDATER` stops only background updates while `claude update` still works. * **TLS** : serve `public_url` over HTTPS in production, either from the gateway’s own listener via `listen.tls` or from a TLS-terminating ingress in front of plain-HTTP replicas, with `listen.public_url` set in both cases. The gateway doesn’t refuse plain HTTP. The IdP must serve HTTPS in production, and Postgres supports `?sslmode=require`. Set `Strict-Transport-Security` at your ingress.
modified Use Claude Code features in the SDK View current →
--- a/claude-code-features.md +++ b/claude-code-features.md @@ -1,4 +1,4 @@ -The Agent SDK is built on the same foundation as Claude Code, which means your SDK agents have access to the same filesystem-based features: project instructions (`CLAUDE.md` and rules), skills, hooks, and more. When you omit `settingSources`, `query()` reads the same filesystem settings as the Claude Code CLI: user, project, and local settings, CLAUDE.md files, and `.claude/` skills, agents, and commands. To run without these, pass `settingSources: []`, which limits the agent to what you configure programmatically. Managed policy settings and the global `~/.claude.json` config are read regardless of this option. See What settingSources does not control. For a conceptual overview of what each feature does and when to use it, see [Extend Claude Code](</docs/en/features-overview>). +The Agent SDK is built on the same foundation as Claude Code, which means your SDK agents have access to the same filesystem-based features: project instructions (`CLAUDE.md` and rules), skills, hooks, and more. When you omit `settingSources`, `query()` reads the same filesystem settings as the Claude Code CLI: user, project, and local settings, CLAUDE.md files, and `.claude/` skills, agents, and commands. To run without these, pass `settingSources: []`, which limits the agent to what you configure programmatically. Managed policy settings and the global `~/.claude.json` config are read regardless of this option. See What settingSources does not control. ## @@ -81,6 +81,7 @@ `~/.claude.json` global config| Always read| Relocate with `CLAUDE_CONFIG_DIR` 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 session authenticates with your claude.ai login. Not loaded when `CLAUDE_CODE_OAUTH_TOKEN` holds a token from [`claude setup-token`](</docs/en/authentication#generate-a-long-lived-token>), which can only make model requests. Passing `mcpServers: {}` does not suppress the connectors| Set `strictMcpConfig: true`, [`disableClaudeAiConnectors: true`](</docs/en/mcp#disable-claude-ai-connectors>) in settings, or `ENABLE_CLAUDEAI_MCP_SERVERS=false` in `env` +[`sandbox.credentials`](</docs/en/sandboxing#protect-credentials>) `deny` entries and file `mask` entries in `~/.claude/settings.json`| When the [command sandbox](</docs/en/sandboxing>) runs, Claude Code applies the `deny` entries and keeps the `credentials.files` `mask` entries as restrictions even when `settingSources` excludes user settings. Claude Code uses these entries only to narrow what sandboxed commands can access| Remove the entries from `~/.claude/settings.json` 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>). @@ -288,8 +289,6 @@ Run deterministic logic on tool calls (audit, block, transform)| [Hooks](</docs/en/agent-sdk/hooks>)| `hooks` parameter with callbacks, or shell scripts loaded via `settingSources` Give Claude structured tool access to an external service| [MCP](</docs/en/agent-sdk/mcp>)| `mcpServers` parameter -**Subagents versus agent teams:** Subagents are ephemeral and isolated: fresh conversation, one task, summary returned to parent. Agent teams coordinate multiple independent Claude Code instances that share a task list and message each other directly. Agent teams are a CLI feature. See [What subagents inherit](</docs/en/agent-sdk/subagents#what-subagents-inherit>) and the [agent teams comparison](</docs/en/agent-teams#compare-with-subagents>) for details. - Every feature you enable adds to your agent’s context window. For per-feature costs and how these features layer together, see [Extend Claude Code](</docs/en/features-overview#understand-context-costs>). ##
modified Use Claude Code on the web View current →
--- a/claude-code-on-the-web.md +++ b/claude-code-on-the-web.md @@ -9,7 +9,7 @@ * Cloud environments: where sessions run, and where to configure that * GitHub authentication options: two ways to connect GitHub * Move tasks between web and terminal with `--cloud` and `--teleport` - * Work with sessions: reviewing, sharing, archiving, deleting + * Work with sessions: permission modes, reviewing, sharing, archiving, deleting * Auto-fix pull requests: respond automatically to CI failures and review comments * Security and isolation: how sessions are isolated * Limitations: rate limits and platform restrictions @@ -20,7 +20,7 @@ Cloud environments -Every cloud session runs in a [cloud environment](</docs/en/cloud-environments>), the saved configuration that controls network access, environment variables, and setup scripts. If you don’t have an environment yet, onboarding sets up a **Default** environment with [**Trusted** network access](</docs/en/cloud-environments#access-levels>), either by creating it for you or by asking you to create it. See [The Default environment](</docs/en/cloud-environments#the-default-environment>) for which of those happens on your plan and how sessions choose an environment when you have more than one. The same environments apply wherever you start a cloud session: the web, the terminal, [Claude Tag](<https://claude.com/docs/claude-tag/overview>), [routines](</docs/en/routines>), and the mobile and Desktop apps. Claude Tag channel sessions use [organization-shared environments](</docs/en/cloud-environments#organization-shared-environments>) only. See [Configure cloud environments](</docs/en/cloud-environments>) to change what an environment allows, set variables, or add a setup script, and [Installed tools](</docs/en/cloud-environments#installed-tools>) for what sessions include without any configuration. +Every cloud session runs in a [cloud environment](</docs/en/cloud-environments>), the saved configuration that controls network access, environment variables, and setup scripts. If you don’t have an environment yet, onboarding sets up a **Default** environment with [**Trusted** network access](</docs/en/cloud-environments#access-levels>), either by creating it for you or by asking you to create it. See [The Default environment](</docs/en/cloud-environments#the-default-environment>) for which of those happens on your plan and how sessions choose an environment when you have more than one. The same environments apply wherever you start a cloud session: the web, the terminal, [Claude Tag](<https://claude.com/docs/claude-tag/overview>), [routines](</docs/en/routines>), and the mobile and Desktop apps. Claude Tag channel sessions use organization-level environments only, either [shared environments](</docs/en/cloud-environments#organization-shared-environments>) or [self-hosted environments](</docs/en/self-hosted-environments>). See [Configure cloud environments](</docs/en/cloud-environments>) to change what an environment allows, set variables, or add a setup script, and [Installed tools](</docs/en/cloud-environments#installed-tools>) for what sessions include without any configuration. ## @@ -37,7 +37,7 @@ With either method, a cloud session can access any repository the connecting GitHub account can see, not just the repositories the Claude GitHub App is installed on. App installation enables PR webhooks for Auto-fix; it is not a session-level access control. To restrict which repositories your team can reach from cloud sessions, restrict access on GitHub itself, for example by limiting team or repository membership for the connected GitHub accounts. -Either method works. [`/schedule`](</docs/en/routines>) checks for either form of access and prompts you to run `/web-setup` if neither is configured. See [Connect from your terminal](</docs/en/web-quickstart#connect-from-your-terminal>) for the `/web-setup` walkthrough. Quick web setup is an organization setting that lets members connect GitHub with `/web-setup`, skips the Claude GitHub App install prompt during browser onboarding, and has browser onboarding create the [**Default** environment](</docs/en/cloud-environments#the-default-environment>) for them instead of showing the environment form. On Team and Enterprise plans it’s off by default, which hides `/web-setup`. An [Owner](</docs/en/server-managed-settings#access-control>) turns it on with the **Quick web setup** toggle at [**Admin settings > Claude Code**](<https://claude.ai/admin-settings/claude-code>). +Either method works. For how `/schedule` checks that access before creating a routine, see [Repositories and branch permissions](</docs/en/routines#repositories-and-branch-permissions>). See [Connect from your terminal](</docs/en/web-quickstart#connect-from-your-terminal>) for the `/web-setup` walkthrough. Quick web setup is an organization setting that lets members connect GitHub with `/web-setup`, skips the Claude GitHub App install prompt during browser onboarding, and has browser onboarding create the [**Default** environment](</docs/en/cloud-environments#the-default-environment>) for them instead of showing the environment form. On Team and Enterprise plans it’s off by default, which hides `/web-setup`. An [Owner](</docs/en/server-managed-settings#access-control>) turns it on with the **Quick web setup** toggle at [**Admin settings > Claude Code**](<https://claude.ai/admin-settings/claude-code>). Organizations with [Zero Data Retention](</docs/en/zero-data-retention>) enabled can’t use `/web-setup` or other cloud session features. @@ -49,7 +49,7 @@ These workflows require the [Claude Code CLI](</docs/en/quickstart>) signed in to the same claude.ai account. You can start new cloud sessions from your terminal, or pull cloud sessions into your terminal to continue locally. Cloud sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude mobile app. -From the CLI, session handoff is one-way: you can pull cloud sessions into your terminal with `--teleport`, but you can’t push an existing terminal session to the web. The `--cloud` flag with a task description creates a new cloud session for your current repository; with a session ID or claude.ai/code URL it instead targets that existing session, [queueing a message or attaching your terminal](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>). The [Desktop app](</docs/en/desktop#continue-in-another-surface>) provides a Continue in menu that can send a local session to the web. +From the CLI, session handoff is one-way: you can pull cloud sessions into your terminal with `--teleport`, but you can’t push an existing terminal session to the web. The `--cloud` flag with a task description creates a new cloud session for your current repository; with `-p` and a session ID or claude.ai/code URL it instead [queues a message into that existing session](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>). The [Desktop app](</docs/en/desktop#continue-in-another-surface>) provides a Continue in menu that can send a local session to the web. ### @@ -112,11 +112,11 @@ Send follow-ups from the CLI -Once a cloud session is running, wherever it executes, send it a follow-up message from the `claude` CLI on any machine where you’re logged in with `claude auth login`. The CLI authenticates with your Anthropic account credentials and sends no local session state, so the command doesn’t need to run from the machine that started the session, and it’s the same in every shell, including PowerShell. The primary form posts one message and exits: +Once a cloud session is running, wherever it executes, send it a follow-up message from the `claude` CLI on any machine where you’re logged in with `claude auth login`. The CLI authenticates with your Anthropic account credentials and sends no local session state, so the command doesn’t need to run from the machine that started the session, and it’s the same in every shell, including PowerShell. The command posts one message and exits: claude -p "your message" --cloud <session-id> -The CLI queues the message into the session and exits without waiting for a reply. Use it to steer a long-running session, queue the next step while the current one is still finishing, or send follow-ups from a [CI script](</docs/en/self-hosted-environments-testing#run-the-test-loop>). You can also pipe the message on stdin instead of passing it as an argument: `echo "your message" | claude -p --cloud <session-id>`. Without `-p`, `claude --cloud <session-id>` attaches your terminal to the session so you can converse with it directly. Interactive attach is rolling out gradually; if you see `Attaching to an existing cloud session is not enabled for your account`, contact your Anthropic account team. The `-p` queue-and-exit form isn’t affected by this rollout. For `<session-id>`, pass the bare ID, such as `session_...` or `cse_...`, or the session’s `claude.ai/code/<id>` URL, with or without the scheme or query string. Find the ID in your session list at claude.ai/code. +The CLI queues the message into the session and exits without waiting for a reply. Use it to steer a long-running session, queue the next step while the current one is still finishing, or send follow-ups from a [CI script](</docs/en/self-hosted-environments-testing#run-the-test-loop>). You can also pipe the message on stdin instead of passing it as an argument: `echo "your message" | claude -p --cloud <session-id>`. For `<session-id>`, pass the bare ID, such as `session_...` or `cse_...`, or the session’s `claude.ai/code/<id>` URL, with or without the scheme or query string. Find the ID in your session list at claude.ai/code. `--cloud` requires an Anthropic account. It’s not available when Claude Code is configured for Amazon Bedrock, Google Cloud’s Agent Platform, or another third-party provider. An [LLM gateway](</docs/en/llm-gateway>) configured only through `ANTHROPIC_BASE_URL` doesn’t count as a third-party provider for this check, but you still need to sign in with `claude auth login`. Your organization’s `allow_remote_sessions` policy must also be enabled. An Owner can turn it on in the Claude Code admin settings at claude.ai/admin-settings/claude-code. @@ -126,7 +126,7 @@ Output and errors -On success, the queue-and-exit form prints the session ID and a link to view the session: +On success, the command prints the session ID and a link to view the session: Sent to cloud session. Session ID: session_01DiUkqY2kzbUbDmW1w96rfi @@ -138,7 +138,7 @@ ---|--- `Cloud sessions aren't available with <provider>. They run on Anthropic's infrastructure and require an Anthropic account.`| Claude Code is configured for a third-party provider. The message names the provider with the label your configuration uses, such as `Amazon Bedrock` or `Google Vertex AI`. Remove that provider’s configuration, for example by unsetting `CLAUDE_CODE_USE_BEDROCK`, and sign in with an Anthropic account (`claude auth login`). `Cloud sessions are disabled by your organization's policy. Contact your organization admin to enable them.`| The `allow_remote_sessions` organization policy is off. -`Attaching to an existing cloud session is not enabled for your account.`| Interactive attach, without `-p`, is rolling out gradually and isn’t available for your account yet. The queue-and-exit form, `-p "..." --cloud <session-id>`, works regardless. +`Attaching to an existing cloud session is not enabled for your account.`| You ran `--cloud <session-id>` without `-p`. Send the message with `claude -p "your message" --cloud <session-id>`. `Session not found: <id>`| The ID or URL doesn’t match a session you can access. Check it against the session’s claude.ai/code URL. `cloud session <id> is archived and cannot accept new messages`| The session has been archived. Start a new session instead. @@ -209,6 +209,14 @@ `/clear`| No| Start a new session from the sidebar instead Auto-compaction runs automatically when the context window approaches capacity. Claude Code on the web sets [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](</docs/en/env-vars>) in cloud sessions itself, so compaction triggers partway through the [auto-compact window](</docs/en/model-config#set-the-auto-compact-window>) rather than when the window fills. That value overrides one you add in your [environment variables](</docs/en/cloud-environments#set-environment-variables>), so adding the variable there doesn’t change when compaction triggers. To change the auto-compact window instead, set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>) in your environment variables, or run [`/autocompact`](</docs/en/commands#all-commands>) with a token count in a session where the variable isn’t set. [Subagents](</docs/en/sub-agents>) work the same way they do locally. Claude can spawn them with the Agent tool to offload research or parallel work into a separate context window, keeping the main conversation lighter. Subagents defined in your repo’s `.claude/agents/` are picked up automatically. [Agent teams](</docs/en/agent-teams>) are off by default but can be enabled by adding `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` to your [environment variables](</docs/en/cloud-environments#set-environment-variables>). + +### + +​ + +Permission modes in cloud sessions + +You pick a cloud session’s [permission mode](</docs/en/permission-modes>) from the [mode dropdown](</docs/en/permission-modes#switch-permission-modes>), both when you create the task and while the session runs. When you reopen a session whose Anthropic-hosted environment expired, or send a message to a session that a self-hosted runner [released while it was idle](</docs/en/self-hosted-environments-reference#runner-cli-flags>), Claude Code resumes the session in the permission mode it was in. ###
modified Claude Code on Claude Platform on AWS View current →
--- a/claude-platform-on-aws.md +++ b/claude-platform-on-aws.md @@ -1,4 +1,4 @@ -Claude Platform on AWS is the Anthropic-operated Claude API with AWS authentication, IAM access control, and AWS Marketplace billing. Requests reach Anthropic’s API directly, so you get the same models and API features as the [Claude API](<https://platform.claude.com/docs>) on the same release schedule. Client-side features that Claude Code turns on through Anthropic’s feature-flag service, such as [`/loop` self-pacing](</docs/en/scheduled-tasks#let-claude-choose-the-interval>), are off by default, and the [advisor tool](</docs/en/advisor>) is not available. See the [feature availability matrix](</docs/en/feature-availability#summary-by-provider>) for the full list. You authenticate with AWS credentials or a workspace API key, and you pay through AWS Marketplace. Use this guide to point Claude Code at a workspace you’ve already provisioned through Claude Platform on AWS. For the AWS subscription and workspace setup that comes before this, see the [Claude Platform on AWS documentation](<https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws>). +Claude Platform on AWS is the Anthropic-operated Claude API with AWS authentication, IAM access control, and AWS Marketplace billing. Requests reach Anthropic’s API directly, so you get the same models and API features as the [Claude API](<https://platform.claude.com/docs>) on the same release schedule. You authenticate with AWS credentials or a workspace API key, and you pay through AWS Marketplace. Client-side features that Claude Code turns on through Anthropic’s feature-flag service are off by default, and the [advisor tool](</docs/en/advisor>) isn’t available. See the [feature availability matrix](</docs/en/feature-availability#summary-by-provider>) for the full list. Use this guide to point Claude Code at a workspace you’ve already provisioned through Claude Platform on AWS. For the AWS subscription and workspace setup that comes before this, see the [Claude Platform on AWS documentation](<https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws>). Subscribing through AWS Marketplace provisions a new Anthropic organization tied to your AWS account. This organization is separate from any organization you already have with Anthropic, and credentials don’t transfer between them. Use the workspace ID and API keys from the AWS-linked organization, not from a pre-existing Claude Console account.
modified Scan your codebase for vulnerabilities View current →
--- a/claude-security.md +++ b/claude-security.md @@ -8,7 +8,7 @@ To run the plugin, you need: - * Claude Code v2.1.154 or later on a paid plan, for the [dynamic workflows](</docs/en/workflows>) the scan uses to orchestrate its agents. On Pro, turn them on from the Dynamic workflows row in `/config`. + * A paid plan, for the [dynamic workflows](</docs/en/workflows>) the scan uses to orchestrate its agents. On Pro, turn them on from the Dynamic workflows row in `/config`. * Python 3.9.6 or later available on your `PATH` as `python3`. Check with `python3 --version`. The plugin’s tooling uses only the Python standard library, so nothing is installed. * Linux, macOS, or Windows. * Git, for change scans and for turning findings into patches; those jobs don’t support other version control systems. A full scan works in any directory, with or without version control.
modified CLI reference View current →
--- a/cli-reference.md +++ b/cli-reference.md @@ -71,7 +71,7 @@ `--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 Anthropic authentication through claude.ai or a Console API key| `claude --channels plugin:my-notifier@my-marketplace` `--chrome`| Enable [Chrome browser integration](</docs/en/chrome>) for web automation and testing| `claude --chrome` -`--cloud`| With a task description, create a new [web session](</docs/en/claude-code-on-the-web>) on claude.ai. With a session ID (`session_...` or `cse_...`) or a claude.ai/code URL, target that existing session instead: `-p` queues the message into it, and no `-p` attaches your terminal. See [send a follow-up message](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>).| `claude --cloud "Fix the login bug"` +`--cloud`| With a task description, create a new [web session](</docs/en/claude-code-on-the-web>) on claude.ai. With a session ID (`session_...` or `cse_...`) or a claude.ai/code URL, queue a message into that existing session instead, with `-p`. See [send a follow-up message](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>).| `claude --cloud "Fix the login bug"` `--continue`, `-c`| Load the most recent conversation in the current directory, skipping [background sessions, sessions created with `claude -p` or the Agent SDK, and sessions whose first prompt was `/loop`](</docs/en/sessions#resume-a-session>). `claude -p --continue` includes `-p`, SDK, and `/loop` sessions. Includes sessions that added this directory with `/add-dir`| `claude --continue` `--dangerously-load-development-channels`| Enable [channels](</docs/en/channels-reference#test-during-the-research-preview>) that are not on the approved allowlist, for local development. Accepts `plugin:<name>@<marketplace>` and `server:<name>` entries. Prompts for confirmation| `claude --dangerously-load-development-channels server:webhook` `--dangerously-skip-permissions`| Skip permission prompts. Equivalent to `--permission-mode bypassPermissions`. See [permission modes](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) for what this does and does not skip. For sessions started with `--bg`, the mode [persists when the supervisor restarts the session](</docs/en/agent-view#permission-mode-model-and-effort>)| `claude --dangerously-skip-permissions` @@ -81,7 +81,7 @@ `--disallowedTools`, `--disallowed-tools`| Deny rules. A bare tool name removes the matching tools from Claude’s context: `"Edit"` removes Edit, `"*"` removes every tool, and `"mcp__*"` removes every MCP tool. A scoped rule such as `Bash(rm *)` leaves the tool available and denies only matching calls. A rule naming [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) can’t remove it while any other tool remains| `"Bash(git log *)" "Bash(git diff *)" "Edit"` `--effort`| Set the [effort level](</docs/en/model-config#adjust-effort-level>) for the current session. Options: `low`, `medium`, `high`, `xhigh`, `max`, or `ultracode`. Available levels depend on the model. `ultracode` starts the session at `xhigh` effort with [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>) turned on, and requires Claude Code v2.1.203 or later. Overrides the [`effortLevel`](</docs/en/settings-reference#effortlevel>) setting for this session and does not persist| `claude --effort high` `--enable-auto-mode`| Removed in v2.1.111. Auto mode is now in the `Shift+Tab` cycle by default; use `--permission-mode auto` to start in it| `claude --permission-mode auto` -`--environment <environment-id>`| Create a new cloud session that runs on the [self-hosted environment](</docs/en/self-hosted-environments>) with the given ID. Environment IDs start with `ccpool_`. See [`--environment` dispatch behavior](</docs/en/self-hosted-environments-testing#environment-dispatch-behavior>) for the interactive and non-interactive forms and the flag combinations it rejects. Requires Claude Code v2.1.224 or later| `claude -p "Fix the login bug" --environment ccpool_abc123` +`--environment <environment-id>`| Create a new cloud session that runs on the [self-hosted environment](</docs/en/self-hosted-environments>) with the given ID. Environment IDs start with `ccpool_`. See [`--environment` dispatch behavior](</docs/en/self-hosted-environments-testing#environment-dispatch-behavior>) for dispatch behavior and the flag combinations it rejects. Requires Claude Code v2.1.224 or later| `claude -p "Fix the login bug" --environment ccpool_abc123` `--exclude-dynamic-system-prompt-sections`| Move per-machine sections from the system prompt (working directory, environment info, memory paths, git-repo flag) into the first user message. Improves prompt-cache reuse across different users and machines running the same task. Only applies with the default system prompt; ignored when `--system-prompt` or `--system-prompt-file` is set. Use with `-p` for scripted, multi-user workloads| `claude -p --exclude-dynamic-system-prompt-sections "query"` `--exec`| Run a shell command as a PTY-backed background job instead of starting a Claude session. Use with `--bg` to launch from the shell| `claude --bg --exec 'pytest -x'` `--fallback-model`| Enable automatic fallback to the specified model(s) when the primary model is overloaded or not available, for example a retired model. Accepts a comma-separated list tried in order. See [Fallback model chains](</docs/en/model-config#fallback-model-chains>). To persist a chain across sessions, use the [`fallbackModel` setting](</docs/en/settings-reference#fallbackmodel>), which this flag overrides| `claude --fallback-model sonnet,haiku` @@ -97,7 +97,7 @@ `--json-schema`| Get validated JSON output matching a JSON Schema after the agent completes its workflow (print mode only). See [structured outputs](</docs/en/agent-sdk/structured-outputs>). Claude Code exits with an error on an invalid schema and accepts the `format` keyword as an annotation without client-side validation| `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` `--maintenance`| Run [Setup hooks](</docs/en/hooks#setup>) with the `maintenance` matcher before the session (print mode only)| `claude -p --maintenance "query"` `--max-budget-usd`| Maximum dollar amount to spend on API calls before stopping (print mode only). Spend from [subagents](</docs/en/sub-agents>) counts toward the cap. Once spend reaches the cap, spawning another subagent fails with `Budget limit reached`, and Claude Code stops background subagents that are still running; the cap-enforcement behaviors require Claude Code v2.1.217 or later| `claude -p --max-budget-usd 5.00 "query"` -`--max-turns`| Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default. With `--input-format stream-json`, a message sent while Claude is working stays queued and runs as its own turn, with its own limit, when the limit ends the current one| `claude -p --max-turns 3 "query"` +`--max-turns`| Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default. With `--input-format stream-json`, a message still queued when the limit ends a turn stays queued and starts a new turn with its own limit| `claude -p --max-turns 3 "query"` `--mcp-config`| Load MCP servers from JSON files or strings (space-separated). When you pass this flag with `-p`, Claude Code waits for still-pending servers to connect before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default; a server with a [cached tool list](</docs/en/mcp#managing-your-servers>) skips the wait and connects on first use. The wait requires Claude Code v2.1.221 or later| `claude --mcp-config ./mcp.json` `--model`| Sets the model for the current session with an alias for the latest model (`sonnet`, `opus`, `haiku`, or `fable`) or a model’s full name. Overrides the [`model`](</docs/en/settings-reference#model>) setting and [`ANTHROPIC_MODEL`](</docs/en/model-config#environment-variables>)| `claude --model claude-sonnet-5` `--name`, `-n`| Set a display name for the session, shown in `/resume` and the terminal title. You can resume a named session with `claude --resume <name>`. In an interactive session, if another live session on this machine already uses the name, Claude Code applies [a variant of it](</docs/en/sessions#name-your-sessions>) instead. @@ -119,6 +119,7 @@ `--remote-control`, `--rc`| Start an interactive session with [Remote Control](</docs/en/remote-control#start-a-remote-control-session>) enabled so you can also control it from claude.ai or the Claude app. Optionally pass a name for the session| `claude --remote-control "My Project"` `--remote-control-session-name-prefix <prefix>`| Prefix for auto-generated [Remote Control](</docs/en/remote-control>) session names when no explicit name is set. Defaults to your machine’s hostname, producing names like `myhost-graceful-unicorn`. Set `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` for the same effect| `claude remote-control --remote-control-session-name-prefix dev-box` `--replay-user-messages`| Re-emit user messages from stdin back on stdout for acknowledgment. Requires `--input-format stream-json` and `--output-format stream-json`| `claude -p --input-format stream-json --output-format stream-json --verbose --replay-user-messages` +`--restricted`| Start in restricted mode. Use it when an evaluation harness drives `claude` on a shared machine and Claude Code must not run commands or read that machine’s user and project settings. Claude Code removes the built-in tools that run commands or code, and WebFetch, unless you name them individually in `--tools`, not through its `default` preset. It also confines the built-in file tools to the [working directories](</docs/en/permissions#working-directories>), loads only [managed settings](</docs/en/managed-settings>) and `--settings`, and refuses [`bypassPermissions`](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>). Requires Claude Code v2.1.248 or later| `claude --restricted -p "query"` `--resume`, `-r`| Resume a specific session by ID or name, or show an interactive picker to choose a session. The picker and name search include sessions that added this directory with `/add-dir`. When you pass a session ID, Claude Code searches the current project directory and its git worktrees, then every other project on this machine. Before v2.1.223, the ID search covered only the current project directory and its git worktrees. [Background sessions](</docs/en/agent-view>) appear in the picker marked with `bg`| `claude --resume auth-refactor` `--safe-mode`| Start with all customizations disabled to troubleshoot a broken configuration: 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. Authentication, model selection, built-in tools, and permissions work normally, which differs from [`--bare`](</docs/en/headless#start-faster-with-bare-mode>). 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. Useful for checking whether a customization is what triggers [automatic model fallback](</docs/en/model-config#automatic-model-fallback>). Sets [`CLAUDE_CODE_SAFE_MODE`](</docs/en/env-vars>)| `claude --safe-mode` `--session-id`| Use a specific session ID for the conversation (must be a valid UUID)| `claude --session-id "550e8400-e29b-41d4-a716-446655440000"`
modified Configure cloud environments View current →
--- a/cloud-environments.md +++ b/cloud-environments.md @@ -1,8 +1,8 @@ Cloud environments require [Claude Code on the web](</docs/en/claude-code-on-the-web>), which is in research preview for Pro, Max, and Team users, and for Enterprise users with [premium seats or Chat + Claude Code seats](<https://support.claude.com/en/articles/11845131-use-claude-code-with-your-team-or-enterprise-plan>). -Each [cloud session](</docs/en/claude-code-on-the-web>) runs in a cloud environment. You can configure an environment to allow or deny network access, set environment variables for the session, and run a setup script before Claude starts working. The same environments apply wherever you start a cloud session: [Claude Code on the web](</docs/en/claude-code-on-the-web>), the terminal with [`claude --cloud`](</docs/en/claude-code-on-the-web#from-terminal-to-web>), [Claude Tag](<https://claude.com/docs/claude-tag/overview>), [routines](</docs/en/routines>), the [Claude mobile app](</docs/en/mobile>), and the [Desktop app](</docs/en/desktop>). Claude Tag sessions can’t run in [self-hosted environments](</docs/en/self-hosted-environments>) yet; the other surfaces can route to any environment. - -[Remote Control](</docs/en/remote-control>) sessions connect the web and mobile interfaces to a session on your own machine, which uses your machine’s network and files, not a cloud environment. Claude Tag channel sessions use shared environments only. +Each [cloud session](</docs/en/claude-code-on-the-web>) runs in a cloud environment. You can configure an environment to allow or deny network access, set environment variables for the session, and run a setup script before Claude starts working. The same environments apply wherever you start a cloud session: [Claude Code on the web](</docs/en/claude-code-on-the-web>), the terminal with [`claude --cloud`](</docs/en/claude-code-on-the-web#from-terminal-to-web>), [Claude Tag](<https://claude.com/docs/claude-tag/overview>), [routines](</docs/en/routines>), the [Claude mobile app](</docs/en/mobile>), and the [Desktop app](</docs/en/desktop>). Each of these surfaces can also route to a [self-hosted environment](</docs/en/self-hosted-environments>). [Availability and limitations](</docs/en/self-hosted-environments#availability-and-limitations>) covers what Claude can’t use yet when a Claude Tag session runs in one. + +[Remote Control](</docs/en/remote-control>) sessions connect the web and mobile interfaces to a session on your own machine, which uses your machine’s network and files, not a cloud environment. Claude Tag channel sessions use organization-level environments only, either shared environments or [self-hosted environments](</docs/en/self-hosted-environments>). ## @@ -88,9 +88,9 @@ Organization-shared environments -On Team and Enterprise plans, an Owner can create cloud environments that are shared with every member of the organization. The same role manages everything else on the **Cloud environments** admin page, including [self-hosted environments](</docs/en/self-hosted-environments>); the Admin role can’t open the page. The full list of roles that can open it is the one for [managing server-managed settings](</docs/en/server-managed-settings#access-control>). Shared environments appear in each member’s environment selector alongside their personal ones, so a team can standardize on one configuration instead of each member recreating it. Create, edit, and archive shared environments from the **Cloud environments** page in [admin settings](<https://claude.ai/admin-settings>). Each shared environment has a name, a network access level, environment variables in `.env` format, and a setup script. Owners choose the organization’s default environment separately, at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>). Values in a shared environment reach every member’s sessions in that environment. Like personal environments, shared environments have no dedicated secrets store, so don’t include secrets. In [Claude Tag](<https://claude.com/docs/claude-tag/overview>) channels, Claude works as your organization’s shared identity, not as any member, so channel sessions use shared environments only. You can set the environment a channel uses in two ways: - - * Set a shared environment as the organization’s default environment at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>). +On Team and Enterprise plans, an Owner can create cloud environments that are shared with every member of the organization. The same role manages everything else on the **Cloud environments** admin page, including [self-hosted environments](</docs/en/self-hosted-environments>); the Admin role can’t open the page. The full list of roles that can open it is the one for [managing server-managed settings](</docs/en/server-managed-settings#access-control>). Shared environments appear in each member’s environment selector alongside their personal ones, so a team can standardize on one configuration instead of each member recreating it. Create, edit, and archive shared environments from the **Cloud environments** page in [admin settings](<https://claude.ai/admin-settings>). Each shared environment has a name, a network access level, environment variables in `.env` format, and a setup script. Owners choose the organization’s default environment separately, at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>). Values in a shared environment reach every member’s sessions in that environment. Like personal environments, shared environments have no dedicated secrets store, so don’t include secrets. In [Claude Tag](<https://claude.com/docs/claude-tag/overview>) channels, Claude works as your organization’s shared identity, not as any member, so channel sessions use organization-level environments only, either shared environments or [self-hosted environments](</docs/en/self-hosted-environments>). You can set the environment a channel uses in two ways: + + * Set a shared or self-hosted environment as the organization’s default environment at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>). * [Pin one to a channel](<https://claude.com/docs/claude-tag/admins/troubleshooting#channel-sessions-use-the-wrong-environment-or-can%E2%80%99t-find-one>) in the Claude Tag admin settings. ## @@ -189,7 +189,7 @@ Your repo’s `.claude/rules/`| Yes| Part of the clone Your repo’s `.claude/skills/`, `.claude/agents/`, `.claude/commands/`| Yes| Part of the clone Plugins declared in `.claude/settings.json`| Yes| Installed at session start from the [marketplace](</docs/en/plugin-marketplaces>) you declared. Requires network access to reach the marketplace source -Your organization’s [server-managed settings](</docs/en/server-managed-settings>)| Yes| Fetched from Anthropic’s servers when the session starts. See [Surface coverage](</docs/en/model-config#surface-coverage>) for how `availableModels` is enforced in cloud sessions. Settings deployed to your device through MDM or managed settings files don’t apply, because the session runs on an Anthropic-managed VM; in a [self-hosted environment](</docs/en/self-hosted-environments>), sessions read the managed settings file in the runner image only when server-managed settings deliver no keys, per [settings precedence](</docs/en/server-managed-settings#settings-precedence>), apart from the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>) +Your organization’s [server-managed settings](</docs/en/server-managed-settings>)| Yes| Fetched from Anthropic’s servers when the session starts. See [Surface coverage](</docs/en/model-config#surface-coverage>) for how `availableModels` is enforced in cloud sessions. Settings deployed to your device through MDM or managed settings files don’t apply, because the session runs on an Anthropic-managed VM; in a [self-hosted environment](</docs/en/self-hosted-environments>), sessions also read the managed settings file in the runner image, per [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) Your user `~/.claude/CLAUDE.md`| No| Lives on your machine, not in the repo Your user `~/.claude/skills/`, `~/.claude/agents/`, `~/.claude/commands/`| No| Live on your machine, not in the repo. Commit them to the repo’s `.claude/` directory instead. Cloud sessions automatically load skills you enable on claude.ai Plugins enabled only in your user settings| No| User-scoped `enabledPlugins` lives in `~/.claude/settings.json`. Declare them in the repo’s `.claude/settings.json` instead, or enable them for your claude.ai account so Claude Code loads them as [synced plugins](</docs/en/plugins-reference#synced-plugins>) @@ -347,7 +347,10 @@ **When they run**| Before Claude Code launches, skipped when a cached environment exists| After Claude Code launches, on every session including resumed **Where they run**| Cloud sessions only| Local and cloud sessions -If you have SessionStart hooks in your user-level `~/.claude/settings.json`, don’t expect them in the cloud: user-level settings stay on your machine. In a cloud session, Claude Code runs hooks from the repository and from your organization’s [server-managed settings](</docs/en/server-managed-settings>). In a [self-hosted environment](</docs/en/self-hosted-environments-configuration#permissions-and-tool-approval>), Claude Code also runs the hooks the operator seeded from the runner host’s `~/.claude/`, and it runs the hooks in the runner image’s managed settings file when neither [server-managed settings nor an MDM-delivered Claude Code policy](</docs/en/settings#precedence-within-the-managed-tier>) supplies the managed tier. +If you have SessionStart hooks in your user-level `~/.claude/settings.json`, don’t expect them in the cloud. User-level settings stay on your machine. Which other hooks run depends on where the session runs: + + * **Anthropic-hosted environment** : Claude Code runs hooks from the repository and from your organization’s [server-managed settings](</docs/en/server-managed-settings>). + * **[Self-hosted environment](</docs/en/self-hosted-environments-configuration#permissions-and-tool-approval>)** : Claude Code also runs the hooks the operator seeded from the runner host’s `~/.claude/`, and the hooks in the runner image’s managed settings file when that file is one of the [managed sources Claude Code applies](</docs/en/managed-settings#how-claude-code-combines-managed-sources>). ### @@ -671,7 +674,7 @@ * [Claude Code on the web](</docs/en/claude-code-on-the-web>): start, manage, and share cloud sessions * [Web quickstart](</docs/en/web-quickstart>): connect GitHub and start your first cloud session - * [Claude Tag](<https://claude.com/docs/claude-tag/overview>): sessions Claude starts from Slack run in the same Anthropic-hosted environments + * [Claude Tag](<https://claude.com/docs/claude-tag/overview>): sessions Claude starts from Slack run in the same environments * [Routines](</docs/en/routines>): scheduled runs use the same environments and network access levels * [Remote Control](</docs/en/remote-control>): run sessions on your own machine’s network and files instead * [Self-hosted environments](</docs/en/self-hosted-environments>): run cloud sessions on your organization’s own infrastructure
modified Code Review View current →
--- a/code-review.md +++ b/code-review.md @@ -399,7 +399,7 @@ Ultrareview requires authentication with a claude.ai account and is not available on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, or to organizations with Zero Data Retention enabled. When ultrareview is not available, `/code-review ultra` runs a local review in your session instead. -To start a cloud review from a script or CI, run `claude -p '/code-review ultra'`. Claude Code launches the review and prints a link for tracking it. Requires Claude Code v2.1.218 or later. When the review would bill [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>), Claude Code stops before launching, because the billing confirmation needs an interactive session. Run the [`claude ultrareview` subcommand](</docs/en/ultrareview#run-ultrareview-non-interactively>) instead; by running it, you consent to the charge. The command was named `/simplify` before v2.1.147, when it applied fixes by default. From v2.1.154, `/simplify` runs a separate cleanup-only review that applies fixes without hunting for bugs. If you scripted `/simplify` for bug-finding, switch to `/code-review --fix`, which is unchanged. +To start a cloud review from a script or CI, run `claude -p '/code-review ultra'`. Claude Code launches the review and prints a link for tracking it. Requires Claude Code v2.1.218 or later. When the review would bill [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>), Claude Code stops before launching, because the billing confirmation needs an interactive session. Run the [`claude ultrareview` subcommand](</docs/en/ultrareview#run-ultrareview-non-interactively>) instead; by running it, you consent to the charge. The command was named `/simplify` before v2.1.147, when it applied fixes by default. `/simplify` runs a separate cleanup-only review that applies fixes without hunting for bugs. If you scripted `/simplify` for bug-finding, switch to `/code-review --fix`. ##
modified Commands View current →
--- a/commands.md +++ b/commands.md @@ -39,7 +39,7 @@ `/branch [name]`| Create a branch of the current conversation at this point, so you can try a different direction without losing the conversation as it stands. Switches you into the branch and preserves the original, which you can return to with `/resume`. To run a copy as a separate [background session](</docs/en/agent-view>) instead of switching into it, use `/fork`; to hand a side task to a [subagent](</docs/en/sub-agents>) that reports back into this conversation, use `/subtask` `/btw [question]`| Ask a [side question](</docs/en/interactive-mode#side-questions-with-%2Fbtw>) about the current session without adding to the conversation. If you run `/btw` without a question, Claude Code shows your most recent side question so you can browse earlier answers; if you haven’t asked one yet, Claude Code prints a usage line. Before v2.1.212, `/btw` required a question `/bug [report]`| Report a bug or share your conversation. You choose how much session history to include and confirm on a consent screen before anything is sent. When you’re signed in to Anthropic on a first-party connection, the report goes to Anthropic; on a third-party provider, or without Anthropic credentials, Claude Code writes the report to a [local archive under `~/.claude/feedback-bundles/`](</docs/en/data-usage#telemetry-services>) that you forward yourself. In the [VS Code extension](</docs/en/vs-code#use-the-prompt-box>), `/bug` opens the extension’s own feedback dialog instead; requires Claude Code v2.1.229 or later. When you run it while Claude is responding, Claude Code opens the dialog immediately. Before v2.1.232, Claude Code queued the command until the turn finished. Alias: `/share`. Before v2.1.212, `/bug` and `/share` were aliases of `/feedback` -`/cd <path>`| Move this session to a new working directory, keeping the conversation and its prompt cache. Type a partial path to see matching directory suggestions; press `Tab` to accept one. The suggestions require Claude Code v2.1.206 or later. Claude Code prompts you to [trust the workspace](</docs/en/permissions#project-allow-rules-and-workspace-trust>) if you haven’t worked in it before, and `--resume` [finds the moved session](</docs/en/sessions#resume-a-session>) afterward. To grant access to an extra directory without moving the session, use `/add-dir`. Restrict or disable `/cd` targets with [`Cd` permission rules](</docs/en/permissions#cd>). Requires Claude Code v2.1.169 or later +`/cd <path>`| Move this session to a new working directory, keeping the conversation. Type a partial path to see matching directory suggestions; press `Tab` to accept one. The suggestions require Claude Code v2.1.206 or later. For what Claude Code applies from the new directory as soon as you move, and how `/cd` differs from `/add-dir`, see [Move the session to another directory](</docs/en/permissions#move-the-session-to-another-directory>). Requires Claude Code v2.1.169 or later `/chrome`| Configure [Claude in Chrome](</docs/en/chrome>) settings `/claude-api [migrate|upgrade|managed-agents-onboard|prompt-audit]`| **[Skill](</docs/en/skills#bundled-skills>).** Load [Claude API](<https://platform.claude.com/docs/en/api/overview>) and Managed Agents reference material for your project’s language. Also activates automatically when your code imports `anthropic` or `@anthropic-ai/sdk`. Run `migrate` to update existing Claude API code to a newer model; `upgrade` to move your project’s Anthropic SDK dependency across a major version, currently the Python `anthropic` package from 0.x to 1.x; `managed-agents-onboard` for a walkthrough that creates a new Managed Agent; or `prompt-audit` to flag instructions written for older models in your prompts, skills, and tool descriptions and propose fixes as a diff. The `prompt-audit` subcommand requires Claude Code v2.1.221 or later, and `upgrade` requires v2.1.236 or later `/clear [name]`| Start a new conversation with empty context. Pass a name to label the previous conversation in the `/resume` picker. To free up context while continuing the same conversation, use `/compact` instead. Resume the previous conversation with `/resume`, or, in the same Claude Code process, restore it from [the rewind menu’s previous-session entry](</docs/en/checkpointing#rewind-past-a-cleared-conversation>). The rewind entry requires Claude Code v2.1.191 or later. Aliases: `/reset`, `/new` @@ -80,7 +80,7 @@ `/list-agents`| List the subagents, [agent team](</docs/en/agent-teams>) teammates, and other Claude Code sessions Claude can message, with the name to use for each. See [cross-session messaging](</docs/en/cross-session-messaging>). Also available as `/peers`. Requires Claude Code v2.1.224 or later; earlier versions report `Unknown command: /list-agents`. Teammate rows and the first line showing this session’s own name require v2.1.239 or later. Available only in sessions where [cross-session messaging is enabled](</docs/en/cross-session-messaging#availability>) `/login`| Sign in to your Anthropic account `/logout`| Sign out from your Anthropic account -`/loop [interval] [prompt]`| **[Skill](</docs/en/skills#bundled-skills>).** Run a prompt repeatedly while the session stays open. Omit the interval and, [where available](</docs/en/scheduled-tasks#let-claude-choose-the-interval>), Claude self-paces between iterations. Omit the prompt and, [where available](</docs/en/scheduled-tasks#let-claude-choose-the-interval>), Claude runs an autonomous maintenance check or the prompt in `.claude/loop.md`. Example: `/loop 5m check if the deploy finished`. See [Run prompts on a schedule](</docs/en/scheduled-tasks>). Alias: `/proactive` +`/loop [interval] [prompt]`| **[Skill](</docs/en/skills#bundled-skills>).** Run a prompt repeatedly while the session stays open. Omit the interval and Claude [self-paces between iterations](</docs/en/scheduled-tasks#let-claude-choose-the-interval>). Omit the prompt and Claude runs the [built-in maintenance prompt](</docs/en/scheduled-tasks#run-the-built-in-maintenance-prompt>) or your [`loop.md`](</docs/en/scheduled-tasks#customize-the-default-prompt-with-loop-md>). Example: `/loop 5m check if the deploy finished`. See [Run prompts on a schedule](</docs/en/scheduled-tasks>). Alias: `/proactive` `/mcp [reconnect <server>|enable|disable [<server>|all]]`| Manage MCP server connections and OAuth authentication. Run with no argument to open the interactive list, pass `reconnect <server>` to reconnect one disconnected server, or pass `enable`/`disable` with a server name or `all` to change connection state without opening the dialog. Also available in non-interactive mode (`-p`), where running it with no argument prints a text summary of server status instead of opening the list; requires Claude Code v2.1.205 or later `/memory`| Edit `CLAUDE.md` files, enable or disable [auto memory](</docs/en/memory#auto-memory>), and view auto memory entries `/mobile`| Show QR code to download the Claude mobile app. Aliases: `/ios`, `/android` @@ -97,7 +97,7 @@ `/recap`| Generate a one-line summary of the current session on demand. See [Session recap](</docs/en/interactive-mode#session-recap>) for the automatic recap that appears after you’ve been away `/release-notes`| View the changelog in an interactive version picker. Select a specific version to see its release notes, or choose to show all versions. The notes appear in your transcript without entering the conversation Claude sees `/reload-plugins [--force]`| Reload all active [plugins](</docs/en/plugins>) to apply pending changes without restarting. Reports counts for each reloaded component and flags any load errors. When the reload would change which MCP tools are loaded and invalidate the prompt cache, the command warns and skips unless you pass `--force` -`/reload-skills`| Re-scan [skill](</docs/en/skills>) and command directories so skills added or changed on disk during the session become available without restarting. Reports how many skills are available and how many were added or removed. Added in v2.1.152 +`/reload-skills`| Re-scan [skill](</docs/en/skills>) and command directories so skills added or changed on disk during the session become available without restarting. Reports how many skills are available and how many were added or removed `/remote-control`| Make this session available for [Remote Control](</docs/en/remote-control>) from claude.ai. Running it while signed out prints that Remote Control requires a claude.ai subscription and tells you how to sign in; before v2.1.206 it reported `Unknown command: /remote-control`. Alias: `/rc` `/remote-env`| Choose the default environment for [cloud agents](</docs/en/cloud-environments#select-an-environment-from-the-cli>) `/rename [name]`| Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history. Also available in non-interactive mode (`-p`); requires Claude Code v2.1.205 or later. From every rename surface, including claude.ai and the desktop app, Claude Code replaces control and invisible characters in the new name with spaces and caps the name at 200 characters. If the name is empty once invisible characters are removed, Claude Code rejects it and shows `That name is empty once invisible characters are removed. Usage: /rename <name>`. The character replacement and length cap require Claude Code v2.1.221 or later. If another live session on this machine already uses a name you pass, Claude Code applies [a variant of it](</docs/en/sessions#name-your-sessions>) instead @@ -112,7 +112,7 @@ `/security-review`| Analyze the changes on your current branch for security vulnerabilities. Reviews the diff between your branch and origin’s default branch, identifying risks like injection, auth issues, and data exposure. Needs an `origin` remote; if the review fails with an `ambiguous argument` error, see the [error reference](</docs/en/errors#security-review-fails-without-origin-head>) `/setup-bedrock`| Configure [Amazon Bedrock](</docs/en/amazon-bedrock>) authentication, region, and model pins through an interactive wizard. Hidden from the command menu until `CLAUDE_CODE_USE_BEDROCK=1` is set; type it in full. First-time Amazon Bedrock users can also access this wizard from the login screen `/setup-vertex`| Configure [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>) authentication, project, region, and model pins through an interactive wizard. Hidden from the command menu until `CLAUDE_CODE_USE_VERTEX=1` is set; type it in full. First-time Google Cloud’s Agent Platform 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 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 +`/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. The review doesn’t look for correctness bugs. Use `/code-review` to find bugs. Pass a path or PR reference to review a specific target `/skills`| List available [skills](</docs/en/skills>). Type to filter the list by name, description, or source. Press `t` to sort by token count, `Space` or `Enter` to [cycle a skill’s visibility to Claude and the `/` menu](</docs/en/skills#override-skill-visibility-from-settings>), and `Esc` to save and close. You can’t cycle plugin skills, skills whose frontmatter sets `disable-model-invocation: true`, or skills with a `skillOverrides` entry in managed settings or the `--settings` flag `/stats`| Alias for `/usage`. Opens on the Stats tab `/status`| Open the Settings interface on the Status tab, showing version, model, account, and connectivity. A `Session kind` row reads `background job · attached` or `background job · unattended` in a [background session](</docs/en/agent-view>), depending on whether a terminal is attached, and `interactive` in any other session. Before v2.1.221, `/status` didn’t show this row. Works while Claude is responding @@ -134,7 +134,7 @@ `/verify`| **[Skill](</docs/en/skills#bundled-skills>).** Confirm a code change does what it should by building your project’s app, running it, and observing the result, rather than relying on tests or type checks. See [Run and verify your app](</docs/en/skills#run-and-verify-your-app>) `/vim`| Removed in v2.1.92. To toggle between Vim and Normal editing modes, use `/config` → Editor mode `/voice [hold|tap|off]`| Toggle [voice dictation](</docs/en/voice-dictation>), or enable it in a specific mode. Requires a Claude.ai account -`/web-setup`| Connect your GitHub account to [Claude Code on the web](</docs/en/web-quickstart#connect-from-your-terminal>) using your local `gh` CLI credentials. `/schedule` prompts for this automatically if GitHub isn’t connected +`/web-setup`| Connect your GitHub account to [Claude Code on the web](</docs/en/web-quickstart#connect-from-your-terminal>) using your local `gh` CLI credentials `/workflows`| Open the [workflow](</docs/en/workflows#watch-the-run>) progress view to watch, pause, resume, or save running and completed workflows ##
modified Track cost and usage View current →
--- a/cost-tracking.md +++ b/cost-tracking.md @@ -1,6 +1,6 @@ The Claude Agent SDK provides detailed token usage information for each interaction with Claude. This guide explains how to properly track usage and understand cost reporting, especially when dealing with parallel tool uses and multi-step conversations. For complete API documentation, see the [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) and [Python SDK reference](</docs/en/agent-sdk/python>). -The `total_cost_usd` and `costUSD` fields are client-side estimates, not authoritative billing data. The SDK computes them locally from a price table bundled at build time, so they can drift from what you are actually billed when: +The `total_cost_usd` and `costUSD` fields are client-side estimates, not authoritative billing data. The SDK computes them locally from a price table bundled at build time, unless a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table is in effect. They can drift from what you are actually billed when: * pricing changes * the installed SDK version does not recognize a model @@ -72,7 +72,7 @@ `total_cost_usd`| Included. Counts subagent requests alongside the top-level loop `modelUsage` / `model_usage`| Included. Counts subagent requests alongside the top-level loop, broken down by model -The following examples iterate over the message stream from a `query()` call and print the total cost when the `result` message arrives: +In [single message input mode](</docs/en/agent-sdk/streaming-vs-single-mode#single-message-input>), when background subagents are still running at the end of the final turn, Claude Code waits for them, up to the cap described in [background tasks at exit](</docs/en/headless#background-tasks-at-exit>), before emitting the result. The result’s `total_cost_usd`, `duration_api_ms`, and `modelUsage`, or `model_usage` in Python, include the work done during that wait. The following examples iterate over the message stream from a `query()` call and print the total cost when the `result` message arrives: TypeScript @@ -171,7 +171,7 @@ Break down usage per model -The result message includes [`modelUsage`](</docs/en/agent-sdk/typescript#modelusage>), a map of model name to per-model token counts and cost. This is useful when you run multiple models (for example, Haiku for subagents and Opus for the main agent) and want to see where tokens are going. The following example runs a query and prints the cost and token breakdown for each model used: +The result message includes [`modelUsage`](</docs/en/agent-sdk/typescript#modelusage>), a map of model name to per-model token counts and cost. This is useful when you run multiple models (for example, Haiku for subagents and Opus for the main agent) and want to see where tokens are going. Each entry’s `costBasis` says which price table priced that model’s latest request: `list` for list price, `managed` for a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table, or `unknown` when neither matched the model ID. The field requires Claude Code v2.1.246 or later. The following example runs a query and prints the cost and token breakdown for each model used: import { query } from "@anthropic-ai/claude-agent-sdk";
modified Manage costs effectively View current →
--- a/costs.md +++ b/costs.md @@ -14,7 +14,7 @@ The Session block in `/usage` shows API token usage and is intended for API users. Claude Max and Pro subscribers have usage included in their subscription, so the session cost figure isn’t relevant for billing purposes. Subscribers see plan usage bars, activity stats, and a usage breakdown on the same screen. -The Session block at the top of `/usage` shows detailed token usage statistics for your current session. Claude Code computes the dollar figure locally from token counts priced at standard list rates, so it doesn’t reflect promotional pricing or contracted discounts and may differ from your actual bill. For authoritative billing, see the Usage page in the [Claude Console](<https://platform.claude.com/usage>). +The Session block at the top of `/usage` shows detailed token usage statistics for your current session. Claude Code computes the dollar figure locally from token counts at list price, unless a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table is in effect. An administrator sets one in your organization’s managed settings so the figure uses your contracted rates, and while a table is in effect the `Total cost` line carries the note `at your organization's configured rates`. The figure is an estimate, so for authoritative billing see the Usage page in the [Claude Console](<https://platform.claude.com/usage>). Total cost: $0.55 Total duration (API): 6m 20s @@ -43,6 +43,19 @@ ​ +Check your usage-credits spend + +`/usage` also shows a usage-credits row while usage credits are on. What the row shows depends on your plan: + + * **Pro and Max** : your spend for the current month, measured against your monthly spend limit when you have set one. When you haven’t set a limit, the row shows `Unlimited` and no spend figure. + * **Team and Enterprise** : your own spend for the current month, measured against any limit your organization set that applies to you. A limit that covers the whole organization doesn’t appear in the row. When you have no limit of your own, the row shows your spend with no limit beside it. While usage credits are off for you, `/usage` shows no usage-credits row. + +When you have a spend limit, the row appears as soon as usage credits are on and shows 0% until you first spend usage credits. Before v2.1.236, `/usage` showed the row only on Pro and Max plans, and a row with a spend limit stayed hidden until you had spent something. + +#### + +​ + When the usage request fails When the request for your plan limits fails, most often because the usage endpoint is rate limited, `/usage` shows the last usage bars it loaded on this machine within the past 60 minutes, along with a `Showing last-known usage` note stating how long ago that data was fetched. Press `r` to retry; a successful retry replaces the last-known bars with fresh data. Without a snapshot from the past 60 minutes, `/usage` reports that the usage endpoint is rate limited and offers the same retry shortcut. Before v2.1.208, a rate-limited request in a session that hadn’t loaded usage yet always showed the error with no bars. @@ -86,6 +99,34 @@ Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry| Your cloud billing console| Your cloud’s budget controls| [OpenTelemetry](</docs/en/monitoring-usage>) or an [LLM gateway](</docs/en/llm-gateway>) [OpenTelemetry export](</docs/en/monitoring-usage>) works on every setup and is the only option that streams per-user token and cost metrics into your own observability stack in near real time. + +### + +​ + +Report spend at your contracted rates + +By default, Claude Code computes every cost figure it shows developers at list price, so if your organization pays contracted rates, the figures in `/usage`, the status line, and OpenTelemetry don’t match your bill. To make them match, set the [`modelPricing`](</docs/en/settings-reference#modelpricing>) managed setting to your rates. The setting changes what Claude Code reports, not what Anthropic charges. Requires Claude Code v2.1.242 or later. + +1 + +Take the rates from your contract + +Enter the per-million-token rates from your contract. Claude Code doesn’t fetch them from the Claude Console, so update the setting when the contract changes. + +2 + +Write the setting + +Set `multiplier` for a flat percentage off list price, list each model’s four per-token rates under `overrides`, or do both. The [`modelPricing` entry](</docs/en/settings-reference#modelpricing>) has the shape and a paste-ready example. + +3 + +Deploy it through managed settings + +Deliver it as [managed settings](</docs/en/managed-settings>): server-managed settings, an MDM policy, `managed-settings.json`, or a [policy helper](</docs/en/managed-settings#compute-the-policy-with-a-helper-program>). Claude Code ignores the key in user, project, and local settings and in `--settings`. + +To confirm the rates are in effect, run `/usage` in a session that has [received the managed settings](</docs/en/managed-settings#read-the-source-in-%2Fstatus>): the Session block’s `Total cost` line carries the note `at your organization's configured rates`. The figures are still estimates, not an invoice. The per-million-token prices in the `/model` picker stay at list price. ###
modified Message your other Claude Code sessions View current →
Show diff (102 lines)
--- a/cross-session-messaging.md +++ b/cross-session-messaging.md @@ -1,6 +1,6 @@ Cross-session messaging requires Claude Code v2.1.224 or later on macOS and Linux, including Linux inside WSL 2. On native Windows, it requires Claude Code v2.1.234 or later. When a session meets the requirements, messaging is on with nothing to enable. See Availability for provider requirements and how to confirm a session has it. -Cross-session messaging lets Claude deliver a message from one of your Claude Code sessions to another. When a change in one session breaks what another is building on, Claude can warn that session before you notice. When one session settles a question another is blocked on, Claude can send the answer across. A message is a piece of text one Claude writes to another, never conversation history or files. To move a whole conversation or its context, [resume the session](</docs/en/sessions#resume-a-session>) instead. Claude uses two tools for this: `ListAgents` to discover which agents it can reach, and `SendMessage` to deliver a message to one of them by name. With the same `SendMessage` tool, Claude can also message [subagents](</docs/en/sub-agents#resume-subagents>) and [agent team](</docs/en/agent-teams>) teammates within a single session or team. This page covers messages between your independent sessions. +Cross-session messaging lets Claude deliver a message from one of your Claude Code sessions to another. When a change in one session breaks what another is building on, Claude can warn that session before you notice. When one session settles a question another is blocked on, Claude can send the answer across. A message is a piece of text one Claude writes to another, never the sender’s conversation history or files. To move a whole conversation or its context, [resume the session](</docs/en/sessions#resume-a-session>) instead. Claude uses two tools for this: `ListAgents` to discover which agents it can reach, and `SendMessage` to deliver a message to one of them by name. With the same `SendMessage` tool, Claude can also message [subagents](</docs/en/sub-agents#resume-subagents>) and [agent team](</docs/en/agent-teams>) teammates within a single session or team. This page covers messages between your independent sessions. ## @@ -41,7 +41,12 @@ Let @api-worker know the schema migration finished -Once you type at least one letter after the `@`, Claude Code suggests your other live sessions on this machine; after a bare `@`, session rows don’t appear. A cloud or Remote Control session appears in the suggestions only after Claude has already listed or messaged your sessions beyond this machine. You can also type the mention without the picker. When more than one live session answers to the mentioned name, Claude asks you which one you mean before sending. For what the message Claude writes looks like when it arrives, including an example of one, see what a message looks like. +The typeahead lists your other live sessions on this machine. Two cases need more than the first letters of a name: + + * **A session beyond this machine** : a cloud or Remote Control session appears in the typeahead only after Claude has listed or messaged your sessions beyond this machine, so ask Claude to list them first. + * **A name with a space or other characters outside letters, digits, hyphens, and underscores** : type it in double quotes, such as `@"release notes"`. When you pick the session from the typeahead, Claude Code inserts the quotes for you. + +You can also type the mention without the picker. When more than one live session answers to the mentioned name, Claude asks you which one you mean before sending. For what the message Claude writes looks like when it arrives, including an example of one, see what a message looks like. ### @@ -49,7 +54,7 @@ Message delivery -The receiving Claude reads the message between tool calls during an active turn, so a running tool is never interrupted. When the receiving session is idle, Claude Code starts a new turn with the message. Claude Code refuses a message in the following cases: +The receiving Claude reads the message between tool calls during an active turn, so a running tool is never interrupted. When the receiving session is idle, Claude Code starts a new turn with the message. When a message that starts a new turn mentions a file as an `@` immediately followed by its path, Claude Code [attaches that file](</docs/en/common-workflows#reference-files-and-directories>) as it exists on the receiving machine, resolving a relative path from the receiving session’s working directory. The receiving session’s [`Read` deny rules](</docs/en/permissions#read-and-edit>) apply to that file, as they do to a file you mention with `@` yourself. When such a message mentions an [MCP resource](</docs/en/mcp#use-mcp-resources>) with `@`, Claude Code attaches that resource from the receiving session’s MCP servers. A path written without the `@` stays plain text and attaches nothing. A message that Claude reads during an active turn arrives as plain text with nothing attached, even if it mentions files or MCP resources with `@`. Claude Code refuses a message in the following cases: * The message is over the size cap. Claude Code refuses it in the sending session, before it leaves. * A rapid burst to a session on this machine has reached what that session’s inbox accepts. Claude Code refuses further messages to that session. @@ -111,7 +116,7 @@ See which sessions Claude can reach -Claude finds a message’s target on its own, so you don’t need to run anything before asking it to send. To see for yourself which sessions Claude can reach, run the `/list-agents` command. The first line is this session’s own name, the one your other sessions use to message it. The rows below it are the sessions Claude can reach, each with the name it answers to: +Claude finds a message’s target on its own, so you don’t need to run anything before asking it to send. To see for yourself which sessions Claude can reach, run the `/list-agents` command. The first line, when present, is this session’s own name, the one your other sessions use to message it. The rows below it are the sessions Claude can reach: * **Subagents** : agents running inside the current session. * **Teammates** : this session’s own [agent team](</docs/en/agent-teams>) teammates. Before v2.1.239, teammates didn’t appear in the listing, though Claude could already message them by name. @@ -119,7 +124,13 @@ * **Your cloud sessions** : your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions, shown while this session is connected to [Remote Control](</docs/en/remote-control>). Claude Code labels them `cloud` in the listing. * **Your Remote Control sessions on other machines** : shown while this session is connected to [Remote Control](</docs/en/remote-control>), and labeled `Remote Control`. Claude Code shows `offline` as the status of a session whose Remote Control connection has dropped. -This session isn’t one of the rows. If Claude addresses a message to this session’s own name, Claude Code refuses it and tells Claude the target is the current session. Before v2.1.239, the listing didn’t show this session’s name, and Claude Code reported a message sent to it as an agent it couldn’t find. Claude Code reads your cloud and Remote Control session lists newest first and stops after a bounded number of pages for each. If your account has more of those sessions than fit, Claude Code doesn’t list the older ones, and Claude can’t message them by name. When this happens, Claude Code says so in the listing, and Claude sees the same note when it sends a message. Claude addresses a session beyond this machine by name, the same as a local session. See Message sessions on other machines for how those messages travel. A session answers to the name you set with the [`/rename`](</docs/en/commands>) command or the [`--name`](</docs/en/cli-reference#cli-flags>) flag. When you don’t set one, Claude Code names the session itself. For an interactive session, that is the name shown in [listings of running sessions](</docs/en/sessions#name-your-sessions>). When you rename a session, Claude Code also updates the shared record your other sessions use to look up the session’s name. If it can’t update that record, it warns you in the `/rename` output that other sessions may still show the old name. Run the session with [`--debug`](</docs/en/cli-reference#cli-flags>), and Claude Code logs the cause of the failed update. When you rename a session, or start or resume an interactive one, with a name another live session on this machine already uses, Claude Code leaves the name with the session that already has it and [renames yours to a variant](</docs/en/sessions#name-your-sessions>). Sessions can still share a name, for example when one of them runs an earlier version of Claude Code or the shared name is one Claude Code generated. Claude Code shows each local session’s working directory in the `/list-agents` output, so you can tell same-named sessions apart when they run in different directories. Claude addresses the message in one of two ways, depending on how many live sessions answer to the name: +This session isn’t one of the rows. If Claude addresses a message to this session’s own name, Claude Code refuses it and tells Claude the target is the current session. Before v2.1.239, the listing didn’t show this session’s name, and Claude Code reported a message sent to it as an agent it couldn’t find. While this session is connected to [Remote Control](</docs/en/remote-control>), Claude Code withholds some details of your local sessions from the `/list-agents` output, without changing what Claude itself sees when it looks for a session to message: + + * **Working directories** : it leaves out each local session’s working directory. + * **Session names** : it leaves out any session name it can’t attribute to a person, so a row left with no name reads `(unnamed session)`. + * **The first line** : it leaves out the line with this session’s own name unless you typed that name at this terminal, with `--name` or with `/rename` and the name, since you launched or last resumed the session. + +When the output lists anything, it ends with a note saying details were withheld. Running `/rename` followed by an unused name at a session’s own keyboard gives that session a name that appears in the output. Claude Code reads your cloud and Remote Control session lists newest first and stops after a bounded number of pages for each. If your account has more of those sessions than fit, Claude Code doesn’t list the older ones, and Claude can’t message them by name. When this happens, Claude Code says so in the listing, and Claude sees the same note when it sends a message. Claude addresses a session beyond this machine by name, the same as a local session. See Message sessions on other machines for how those messages travel. A session answers to the name you set with the [`/rename`](</docs/en/commands>) command or the [`--name`](</docs/en/cli-reference#cli-flags>) flag. When you don’t set one, Claude Code names the session itself. For an interactive session, that is the name shown in [listings of running sessions](</docs/en/sessions#name-your-sessions>). When you rename a session, Claude Code also updates the shared record your other sessions use to look up the session’s name. If it can’t update that record, it warns you in the `/rename` output that other sessions may still show the old name. Run the session with [`--debug`](</docs/en/cli-reference#cli-flags>), and Claude Code logs the cause of the failed update. When you rename a session, or start or resume an interactive one, with a name another live session on this machine already uses, Claude Code leaves the name with the session that already has it and [renames yours to a variant](</docs/en/sessions#name-your-sessions>). Sessions can still share a name, for example when one of them runs an earlier version of Claude Code or the shared name is one Claude Code generated. Unless this session is connected to Remote Control, Claude Code shows each local session’s working directory in the `/list-agents` output, so you can tell same-named sessions apart when they run in different directories. Claude addresses the message in one of two ways, depending on how many live sessions answer to the name: * **One session answers to the name** : Claude Code delivers the message on the name alone. * **Several sessions share the name, or Claude Code couldn’t check everywhere your sessions run** : Claude adds a short identifier to each row of its listing and uses the identifier in the address. @@ -164,7 +175,7 @@ * Press `Ctrl+O` to open the [transcript viewer](</docs/en/interactive-mode#transcript-viewer>) and read the full text under the sender’s session name. * In a session started with [`--verbose`](</docs/en/cli-reference#cli-flags>), Claude Code shows the full text instead of the preview. -The preview shortens only what you see. Whether or not you expand it, Claude reads the full message. Claude receives the message with the sender’s name and a reply address, except for a one-way cross-machine message, which carries no reply address. Beyond the name and reply address, the receiving Claude gets only the message’s text, never the sender’s conversation history or files. This example is a message one Claude wrote to another, as its full text reads when you expand it: +The preview shortens only what you see. Whether or not you expand it, Claude reads the full message. Claude receives the message with the sender’s name and a reply address, except for a one-way cross-machine message, which carries no reply address. Beyond the name and reply address, the receiving Claude gets the message’s text, never the sender’s conversation history or files. An `@` mention in the text can still attach a file or MCP resource on the receiving side, as described under Message delivery. A message that a [subagent](</docs/en/sub-agents>) wrote arrives under the sending session’s name, with the subagent identified in the message text. A reply to it reaches that session’s main conversation, not the subagent. This example is a message one Claude wrote to another, as its full text reads when you expand it: Schema migration finished The new column is tenant_id, and rebasing on main is safe now. @@ -222,10 +233,9 @@ * `/status` shows it in the `Peer address` row. The path is prefixed with `uds:`. * Claude Code exports it to [hooks](</docs/en/hooks>) and Bash commands as the [`CLAUDE_CODE_MESSAGING_SOCKET`](</docs/en/env-vars#variables>) environment variable: * In a session that starts with messaging on, Claude Code exports the variable before any hook runs, including `SessionStart`. - * When a session starts before Claude Code has fetched the feature flag that turns messaging on, such as the first session after you install Claude Code or upgrade from a version without messaging, Claude Code binds the inbox and exports the variable as soon as the fetch completes. Hooks and processes that started before that point keep the variable unset, while later hooks and Bash commands see it. * Each session exports its own socket, never one inherited from a parent session. -On macOS and Linux, Claude Code restricts the socket to your operating-system user. On native Windows, it instead requires each connection to authenticate first with a key that only your operating-system user can read. Either way, on a shared machine another user’s sessions can’t deliver to it. Alongside the socket’s path, Claude Code exports a per-session token as [`CLAUDE_CODE_MESSAGING_TOKEN`](</docs/en/env-vars#variables>). A script posting to its own session’s socket can send `{"type":"auth","token":"<token>"}` as the first line of its connection, where `<token>` is the value of `CLAUDE_CODE_MESSAGING_TOKEN`. Whether Claude Code requires the line depends on the platform: +On macOS and Linux, Claude Code restricts the socket to your operating-system user. On native Windows, it instead requires each connection to authenticate first with a key that only your operating-system user can read. Either way, on a shared machine another user’s sessions can’t deliver to it. On macOS and Linux, Claude Code also refuses to create the socket in a directory it can’t accept, for example one that another user owns, and uses a private per-user directory, `/tmp/cc-socks-<uid>`, instead. When it can’t accept any directory, the session runs without an inbox: Claude Code shows a notice, `/status` shows `unavailable` and the reason in its `Peer address` row, and the [`--debug`](</docs/en/cli-reference#cli-flags>) log records the full refusal. Alongside the socket’s path, Claude Code exports a per-session token as [`CLAUDE_CODE_MESSAGING_TOKEN`](</docs/en/env-vars#variables>). A script posting to its own session’s socket can send `{"type":"auth","token":"<token>"}` as the first line of its connection, where `<token>` is the value of `CLAUDE_CODE_MESSAGING_TOKEN`. Whether Claude Code requires the line depends on the platform: * **macOS and Linux, including WSL 2** : the line is optional. Claude Code accepts a connection with or without it. * **Native Windows** : the line is required. Claude Code closes any connection whose first line isn’t a valid auth line and delivers nothing from that connection. @@ -288,11 +298,11 @@ Availability -Cross-session messaging requires Claude Code v2.1.224 or later on macOS, Linux, and WSL 2, and v2.1.234 or later on native Windows. Availability also depends on your platform, provider, and configuration: +Cross-session messaging requires Claude Code v2.1.224 or later on macOS, Linux, and WSL 2, and v2.1.234 or later on native Windows. Availability, and which sessions Claude can message, also depend on your operating system, provider, and configuration: * **Operating system** : available on macOS, Windows, and Linux, including Linux inside WSL 2. - * **Provider** : not available on Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry. - * **Feature-flag evaluation** : when any of [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `DISABLE_GROWTHBOOK`](</docs/en/env-vars#variables>) turns off the feature-flag evaluation the feature depends on, cross-session messaging stays off. Each variable’s row says which values do that. Unset whichever applies. These variables can come from your shell, from a settings file’s `env` map, or from managed settings. + * **Sessions on this machine** : available on every provider, including Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, and Microsoft Foundry, and in sessions that run with [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>) off. On those providers, and with flag fetching off, same-machine messaging requires Claude Code v2.1.248 or later. Claude Code delivers these messages over a per-session socket on your machine, never through Anthropic servers. To stop a session from receiving them, set `crossSessionInbound` to `refuse`. + * **Sessions beyond this machine** : Claude finds your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions and your sessions on other machines from a session that is connected to Remote Control, which needs a claude.ai sign-in as this session’s active authentication and the other [Remote Control requirements](</docs/en/remote-control#requirements>). Claude can’t find those sessions with an API key or on Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, and Microsoft Foundry. To check a session, type `/list-agents`, also available as `/peers`. The result separates a session that doesn’t have the feature from a session where something narrower blocked a message, such as a missing `SendMessage` tool or a refused send: @@ -305,7 +315,7 @@ * **Older cloud or other-machine session missing** : Claude Code reads those session lists newest first and stops after a bounded number of pages, so Claude can’t message a session that fell past them by name. * **Starting a conversation** : Message sessions on other machines covers starting a conversation with a session beyond this machine. -In a session with messaging, `/status` also shows a `Peer address` row with the session’s own inbox address. +In a session with messaging, `/status` also shows a `Peer address` row with the session’s own inbox address, or `unavailable` and the reason when Claude Code couldn’t set up an inbox. ##
modified Launch sessions from links View current →
--- a/deep-links.md +++ b/deep-links.md @@ -11,7 +11,7 @@ ​ -How it works +How deep links work The `claude-cli://` prefix is a custom URL scheme that Claude Code registers with your operating system, similar to how `mailto:` links open your email client. When you click a deep link: @@ -114,6 +114,8 @@ open "claude-cli://open?repo=acme/payments&q=review%20open%20PRs" +On success, a new terminal window opens with Claude Code running and the prompt pre-filled. + Most desktop environments provide `xdg-open`, which passes the URL to the registered handler: xdg-open "claude-cli://open?repo=acme/payments&q=review%20open%20PRs" @@ -127,6 +129,8 @@ In `cmd.exe`, `start` treats its first quoted argument as a window title, so pass an empty title before the URL: start "" "claude-cli://open?repo=acme/payments&q=review%20open%20PRs" + +On success, a new terminal window opens with Claude Code running and the prompt pre-filled. ##
modified Desktop application View current →
--- a/desktop.md +++ b/desktop.md @@ -769,16 +769,17 @@ `disableBrowserExternalNavigation`| set to `true` to turn off external browsing in the Browser pane entirely. Neither users nor Claude can navigate to external sites, and localhost dev server previews are unaffected. The value must be the JSON boolean `true`; the string `"true"` is ignored. `sshConfigs`| pre-configure SSH connections that appear in the environment dropdown. Users cannot edit or delete managed connections. `sshHostAllowlist`| restrict SSH sessions to hosts whose resolved hostname matches one of these patterns. An empty array disables SSH sessions. Read from managed settings only. -`disableDesktopLocalSessions`| set to `true` to turn off Code sessions that run on the device, leaving SSH sessions to other hosts and cloud sessions available. The value must be the JSON boolean `true`. Read from managed settings only. +`disableDesktopLocalSessions`| set to `true` to turn off Code sessions that run on the device, leaving SSH sessions to other hosts and cloud sessions available. The value must be the JSON boolean `true`. Read from managed settings only. Requires Claude Desktop v1.37937.0 or later. `managedMcpServers`| push MCP server configurations to all users. Available in third-party (3P) Desktop deployments only. In each entry, set a transport of `"http"`, `"sse"`, or `"stdio"`, connection details, and optionally a `toolPolicy` map to restrict which of that server’s tools users can invoke. Deliver it through the managed settings file, MDM, or a Claude apps gateway policy’s [`desktop` block](</docs/en/claude-apps-gateway-config#claude-desktop-overlay>), since 3P deployments don’t receive admin-console settings. To deliver it through the gateway, you need Claude Code v2.1.232 or later on the gateway server. Which managed settings reach a Desktop session depends on where that session runs. Model restrictions such as [`availableModels`](</docs/en/model-config#restrict-model-selection>) are enforced in Desktop’s Claude Code sessions the same way as in the terminal CLI; see [surface coverage](</docs/en/model-config#surface-coverage>). * **Local sessions on this machine** : a managed settings file deployed to disk applies. Managed settings pushed remotely through the admin console also reach these sessions on Anthropic’s API when the session authenticates with an [eligible login or key](</docs/en/server-managed-settings#platform-availability>), following the same [settings precedence](</docs/en/settings#settings-precedence>) as the terminal CLI. - * **Cloud sessions** : receive [server-managed settings](</docs/en/server-managed-settings>); device-deployed files don’t reach them, because they run on Anthropic-managed VMs. Sessions routed to a [self-hosted environment](</docs/en/self-hosted-environments>) fall back to the managed settings file in the runner image when server-managed settings deliver no keys, per [settings precedence](</docs/en/server-managed-settings#settings-precedence>), apart from the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>). + * **Cloud sessions** : receive [server-managed settings](</docs/en/server-managed-settings>); device-deployed files don’t reach them, because they run on Anthropic-managed VMs. Sessions routed to a [self-hosted environment](</docs/en/self-hosted-environments>) also read the managed settings file in the runner image. [How Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) says when that file applies. * **SSH sessions** : the session reads the managed settings file from the remote host. Desktop itself reads `sshConfigs`, `sshHostAllowlist`, and `disableDesktopLocalSessions` from the local machine’s managed settings. - -`permissions.disableBypassPermissionsMode` and `disableAutoMode` also work in user and project settings, but placing them in managed settings prevents users from overriding them. For the permission, plugin, and delivery keys only a managed source can set, see [Keys only managed settings can set](</docs/en/managed-settings#managed-only-settings>). + * **[Cowork](<https://claude.com/docs/cowork/overview>) sessions**: in a Cowork session on this machine, Claude Code never fetches admin-console settings, even when the user signs in with a Team or Enterprise account, and reads policy deployed to the machine unless your Claude Desktop configuration sets `requireCoworkFullVmSandbox`. Remote Cowork sessions receive neither. See [where and when a policy applies](</docs/en/managed-settings#where-and-when-a-policy-applies>) for which device files reach Cowork, and [MCP permission rules](</docs/en/permissions#mcp>) for how `Bash` and `WebFetch` rules apply to Cowork’s tools. + +In local and SSH sessions, the desktop app delivers each user’s connected claude.ai connectors to Claude Code directly. No MCP setting or `managed-mcp.json` reaches those connectors, whichever settings source or file location you use. To block a connector’s tools in these sessions, use your organization’s [connector tool controls](</docs/en/mcp#organization-controls-on-connector-tools>). [How connectors reach Claude Code](</docs/en/mcp#how-connectors-reach-claude-code>) shows which settings govern connectors in each kind of session. `permissions.disableBypassPermissionsMode` and `disableAutoMode` also work in user and project settings, but placing them in managed settings prevents users from overriding them. For the permission, plugin, and delivery keys only a managed source can set, see [Keys only managed settings can set](</docs/en/managed-settings#managed-only-settings>). ### @@ -830,7 +831,7 @@ *.claudeusercontent.com *.claudemcpcontent.com -If your organization has [IP allowlisting](<https://support.claude.com/en/articles/13200993-restrict-access-to-claude-with-ip-allowlisting>) enabled for Claude, route `bridge.claudeusercontent.com` through the same proxy egress as `claude.ai` and `api.anthropic.com`. If you can’t route it that way, add the egress address your proxy uses for that host to your organization’s IP allowlist, but only when that address is dedicated to your organization: a shared proxy egress range also admits the proxy vendor’s other customers. Anthropic checks connections to that host against your organization’s IP allowlist using the address they arrive from. If your proxy sends traffic for it out through an address that isn’t on that allowlist, Claude in Chrome and other features that connect through the bridge stop working while the rest of the app keeps working. An [artifact](</docs/en/artifacts>) that loads a typeface from [Google Fonts](</docs/en/artifacts#improve-the-visual-design>) also requests `fonts.googleapis.com` and `fonts.gstatic.com`. Both hosts are optional. If you block them, artifacts render in fallback typefaces. Block with a fast rejection rather than a silent drop so the font request fails immediately instead of delaying the page’s first render. +If your organization has [IP allowlisting](<https://support.claude.com/en/articles/13200993-restrict-access-to-claude-with-ip-allowlisting>) enabled for Claude, route `bridge.claudeusercontent.com` through the same proxy egress as `claude.ai` and `api.anthropic.com`. If you can’t route it that way, add the egress address your proxy uses for that host to your organization’s IP allowlist, but only when that address is dedicated to your organization: a shared proxy egress range also admits the proxy vendor’s other customers. Anthropic checks connections to that host against your organization’s IP allowlist using the address they arrive from. If your proxy sends traffic for it out through an address that isn’t on that allowlist, Claude in Chrome and other features that connect through the bridge stop working while the rest of the app keeps working. An [artifact](</docs/en/artifacts>) that loads a typeface from [Google Fonts](</docs/en/artifacts#improve-the-visual-design>) also requests `fonts.googleapis.com` and `fonts.gstatic.com`. Both hosts are optional. If you block them, artifacts render in fallback typefaces. Block with a fast rejection rather than a silent drop so the font request fails immediately instead of delaying the page’s first render. Artifacts can also load JavaScript libraries, such as React or a charting package, from `cdnjs.cloudflare.com`, `cdn.jsdelivr.net`, `cdn.tailwindcss.com`, and `code.jquery.com`, and from no other external host. If you block those hosts, the parts of an artifact that depend on a library don’t work, and unlike a blocked font, a blocked library has no fallback. Block with a fast rejection here too, so a blocked library request fails at once rather than hanging until it times out. ###
modified Schedule recurring tasks in Claude Code Desktop View current →
--- a/desktop-scheduled-tasks.md +++ b/desktop-scheduled-tasks.md @@ -30,7 +30,7 @@ Create a scheduled task -On Claude Desktop before 1.1.5368, local scheduled tasks aren’t available. In the [**Code** tab](</docs/en/desktop>), click **Routines** in the sidebar, then click **New routine** and choose **Local**. If **Routines** is missing from the sidebar, update the Desktop app, and check whether [routines are turned off for your organization](</docs/en/routines#routines-are-disabled-by-your-organizations-policy>). Configure these fields: +On Claude Desktop before 1.1.5368, local scheduled tasks aren’t available. In the [**Code** tab](</docs/en/desktop>), click **Routines** in the sidebar, then click **New routine** and choose **Local**. If **Routines** is missing from the sidebar, update the Desktop app; [Create a routine](</docs/en/routines#create-a-routine>) says which plan and settings routines need. Configure these fields: Field| Description ---|--- @@ -79,7 +79,7 @@ Permissions for scheduled tasks -Each task has its own permission mode, which you set when creating or editing the task. Allow rules from `~/.claude/settings.json` also apply to scheduled task sessions. If a task runs in [Manual mode](</docs/en/desktop#choose-a-permission-mode>) and needs to run a tool it doesn’t have permission for, the run stalls until you approve it. The session stays open in the sidebar so you can answer later. To avoid stalls, click **Run now** after creating a task, watch for permission prompts, and select “always allow” for each one. Future runs of that task auto-approve the same tools without prompting. You can review and revoke these approvals from the task’s detail page. Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) prompt on every call and don’t offer an always-allow option. Runs that call these tools stall each time. +Each task has its own permission mode, which you set when creating or editing the task. Allow rules from `~/.claude/settings.json` also apply to scheduled task sessions. If a task runs in [Manual mode](</docs/en/desktop#choose-a-permission-mode>) and needs to run a tool it doesn’t have permission for, the run stalls until you approve it. The session stays open in the sidebar so you can answer later. To avoid stalls, click **Run now** after creating a task, watch for permission prompts, and select “always allow” for each one. Future runs of that task auto-approve the same tools without prompting. You can review and revoke these approvals from the task’s detail page. MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) prompt on every call and don’t offer an always-allow option. Runs that call these tools stall each time. ##
modified Environment variables View current →
--- a/env-vars.md +++ b/env-vars.md @@ -90,7 +90,7 @@ Precedence -Some behaviors have both an environment variable and a dedicated settings key, and which one Claude Code reads first differs per key. For `ANTHROPIC_MODEL` and `CLAUDE_CODE_AUTO_CONNECT_IDE`, Claude Code reads the variable first and uses the `model` or `autoConnectIde` setting only when the variable is unset. For the pair you’re setting, check the variable’s row below and the key’s entry on the [settings reference](</docs/en/settings-reference>). When the same variable is set in both your shell and a settings file `env` block, the settings file value applies. Claude Code writes each `env` entry into the process environment at startup and again when the file changes, replacing the value inherited from the shell. A few variables are special-cased; the [`env` setting](</docs/en/settings-reference#env>) lists the exceptions. In a settings file you can set a variable but you can’t remove one. To override a variable you can’t unset, such as a stale `CLAUDE_CODE_USE_VERTEX` exported by a shell profile you don’t control, set it to an empty string in the `env` block: `"CLAUDE_CODE_USE_VERTEX": ""`. Claude Code treats the empty value as unset for provider selection. Subprocesses still inherit the empty value. Between settings files, `env` values follow [settings precedence](</docs/en/settings#settings-precedence>), so a managed settings entry overrides the same variable in user or project settings. How an environment variable interacts with CLI flags and in-session commands varies per feature: `--model` and `/model` override `ANTHROPIC_MODEL`, while `CLAUDE_CODE_EFFORT_LEVEL` overrides `/effort`. When a variable interacts with another configuration source, its row in the Variables list states the precedence or links to the page that documents it. Claude Code reads shell environment variables at startup, so changes to them take effect the next time you launch `claude`. Variables set under the `env` key in settings files are reapplied to a running session when the file changes, with the startup-only exception described in In settings files. +Some behaviors have both an environment variable and a dedicated settings key, and which one Claude Code reads first differs per key. For `ANTHROPIC_MODEL` and `CLAUDE_CODE_AUTO_CONNECT_IDE`, Claude Code reads the variable first and uses the `model` or `autoConnectIde` setting only when the variable is unset. For the pair you’re setting, check the variable’s row below and the key’s entry on the [settings reference](</docs/en/settings-reference>). When the same variable is set in both your shell and a settings file `env` block, the settings file value applies. Claude Code writes each `env` entry into the process environment, replacing the value inherited from the shell. The [`env` setting](</docs/en/settings-reference#when-claude-code-applies-env-values>) says when it applies them. A few variables are special-cased; the [`env` setting](</docs/en/settings-reference#env>) lists the exceptions. In a settings file you can set a variable but you can’t remove one. To override a variable you can’t unset, such as a stale `CLAUDE_CODE_USE_VERTEX` exported by a shell profile you don’t control, set it to an empty string in the `env` block: `"CLAUDE_CODE_USE_VERTEX": ""`. Claude Code treats the empty value as unset for provider selection. Subprocesses still inherit the empty value. Between settings files, `env` values follow [settings precedence](</docs/en/settings#settings-precedence>), so a managed settings entry overrides the same variable in user or project settings. How an environment variable interacts with CLI flags and in-session commands varies per feature: `--model` and `/model` override `ANTHROPIC_MODEL`, while `CLAUDE_CODE_EFFORT_LEVEL` overrides `/effort`. When a variable interacts with another configuration source, its row in the Variables list states the precedence or links to the page that documents it. Claude Code reads shell environment variables at startup, so changes to them take effect the next time you launch `claude`. Variables set under the `env` key in settings files are reapplied to a running session when the file changes, with the startup-only exception described in In settings files. ## @@ -186,8 +186,8 @@ `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT`| Set to `1` to send the [effort](</docs/en/model-config#adjust-effort-level>) parameter with every request, even when Claude Code does not recognize the model ID as effort-capable. Use this when routing through an [LLM gateway](</docs/en/llm-gateway>) or third-party provider that serves models under custom identifiers. Models that reject the effort parameter at the API, including Claude 3 models, Sonnet 4.0 and 4.5, Opus 4.0 and 4.1, and Haiku 4.5, are still excluded so requests do not fail `CLAUDE_CODE_API_KEY_HELPER_TTL_MS`| Interval in milliseconds at which credentials should be refreshed (when using [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>)) `CLAUDE_CODE_ARTIFACT_AUTO_OPEN`| Set to `0` to stop Claude Code from opening the browser automatically when a new [artifact](</docs/en/artifacts>) is published. Republishing an existing artifact does not open the browser regardless of this setting -`CLAUDE_CODE_ARTIFACT_COMMENTS`| Set to `1` to let Claude read and reply to [comments on an artifact](</docs/en/artifacts#collect-comments-on-an-artifact>) when feature-flag fetching is off. Set to `0` to turn comment reading and replying off even when fetching is on. Has no effect when `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` has [turned artifacts off](</docs/en/artifacts#availability>). Requires Claude Code v2.1.221 or later -`CLAUDE_CODE_ARTIFACT_COMMENTS_AUTOREACT`| Set to `1` to let Claude [reply on its own to comments sent to it](</docs/en/artifacts#let-claude-reply-to-comments-on-its-own>) when feature-flag fetching is off, or `0` to turn that off even when fetching is on. Needs comment reading on as well. Requires Claude Code v2.1.228 or later +`CLAUDE_CODE_ARTIFACT_COMMENTS`| Set to `0` to stop Claude reading and replying to [comments on an artifact](</docs/en/artifacts#collect-comments-on-an-artifact>). Has no effect when `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` has [turned artifacts off](</docs/en/artifacts#availability>). Requires Claude Code v2.1.221 or later +`CLAUDE_CODE_ARTIFACT_COMMENTS_AUTOREACT`| Set to `0` to stop Claude [replying on its own to comments sent to it](</docs/en/artifacts#let-claude-reply-to-comments-on-its-own>). Requires Claude Code v2.1.228 or later `CLAUDE_CODE_ATTRIBUTION_HEADER`| Set to `0` to omit the [attribution block](</docs/en/llm-gateway-protocol#system-prompt-attribution-block>), which carries the client version and a prompt fingerprint, from the start of the system prompt. Caching on a direct connection to the Anthropic API is unaffected either way. In some direct-connection setups, Claude Code keeps the block on [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier requests even when you set `0`. In [System prompt attribution block](</docs/en/llm-gateway-protocol#system-prompt-attribution-block>), check which connections and credentials this covers. Before v2.1.181 the block included a per-request token on custom base URLs and Microsoft Foundry connections, so on those versions set it to `0` when your LLM gateway caches on the request body or forwards requests to a third-party provider, or when you connect to Microsoft Foundry directly `CLAUDE_CODE_AUTO_COMPACT_WINDOW`| Set the [auto-compact window](</docs/en/model-config#set-the-auto-compact-window>) in tokens, from `100000` to `1000000`. Accepts a plain integer such as `500000` only: a value like `500k` reads as `500` and clamps to the 100K minimum. Takes precedence over the `/autocompact` command, the `--autocompact` flag, and the `autoCompactWindow` setting. The status line’s `used_percentage` always measures against the model’s full context window, so once this variable is set, that percentage no longer indicates when compaction will run `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-reference#autoconnectide>) global config setting @@ -208,7 +208,7 @@ `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 `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-reference#disableagentview>) 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-reference#tui>) 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-reference#disableartifact>) setting +`CLAUDE_CODE_DISABLE_ARTIFACT`| Set to `1` to turn off the [Artifact](</docs/en/artifacts>) tool, which publishes session output as a private web page on claude.ai. Once you set it, no settings file turns the tool back on. To turn the tool off from a settings file instead, set [`enableArtifact`](</docs/en/settings-reference#enableartifact>) to `false`; the deprecated [`disableArtifact`](</docs/en/settings-reference#disableartifact>) key also turns it off `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-reference#automemoryenabled>) 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 @@ -314,6 +314,7 @@ `CLAUDE_CODE_PROXY_RESOLVES_HOSTS`| Set to `1` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution `CLAUDE_CODE_REMOTE`| Set automatically to `true` when Claude Code is running as a [cloud session](</docs/en/claude-code-on-the-web>). Read this from a hook or setup script to detect whether you are in a cloud session `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/cloud-environments#link-output-back-to-the-session>) +`CLAUDE_CODE_RESTRICTED`| Set to `1` to start the session in restricted mode, the same as passing [`--restricted`](</docs/en/cli-reference#cli-flags>). Claude Code ignores this variable in a settings file’s `env` block. Requires Claude Code v2.1.248 or later `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. To turn this off, unset the variable or set it to `0`. Before v2.1.221, Claude Code ignored `0` and other falsy values, so setting `0` still triggered the resume in non-interactive mode and unsetting the variable was the only way to turn it off `CLAUDE_CODE_RESUME_INTERRUPTED_TURN_MAX_AGE_MS`| Maximum age in milliseconds of the last transcript message for a session that ended mid-turn to continue automatically on resume. When the last message is older than this bound, Claude Code skips both the `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` automatic resume and the injected `CLAUDE_CODE_RESUME_PROMPT` continuation message, and the session starts idle so you continue explicitly. Unset or `0` means no bound; a negative or non-numeric value applies a one-hour bound. Spawn scripts for long-running agents can set this so a restart against an old transcript doesn’t re-run a stale prompt. Claude Code sets a one-hour bound itself when it restarts a crashed [agent view](</docs/en/agent-view>) session that inherited its conversation from an interactive session. Requires Claude Code v2.1.211 or later `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 @@ -351,7 +352,8 @@ `CLAUDE_CODE_TEAM_TEARDOWN_PARK_TIMEOUT_MS`| Override, in milliseconds, how long a non-interactive session waits at exit for its [agent team](</docs/en/agent-teams>) to finish tearing down. Accepts 1000 to 60000; an out-of-range value is ignored and the default of 10000 applies. Requires Claude Code v2.1.206 or later `CLAUDE_CODE_TMPDIR`| Override the temp directory used for internal temp files. Claude Code appends `/claude-{uid}/` on Unix or `/claude/` on Windows to this path. Default: `/tmp` on macOS, `os.tmpdir()` on Linux and Windows. As of v2.1.161, on macOS and Linux, [sandboxed](</docs/en/sandboxing>) Bash subprocesses receive a short fallback `$TMPDIR` under the system default when your override is a long path, since some tools fail when temp paths get too long. Unsandboxed Bash commands inherit your shell’s `$TMPDIR` unchanged. Claude Code’s own temp files always use your override `CLAUDE_CODE_TMUX_TRUECOLOR`| Set to any non-empty value, such as `1`, to allow 24-bit truecolor output inside tmux. **Setting it to`0` or `false` still allows truecolor**, unlike most on/off variables; unset the variable to restore the 256-color clamp. By default, Claude Code clamps to 256 colors when `$TMUX` is set because tmux does not pass through truecolor escape sequences unless configured to. Set this after adding `set -ga terminal-overrides ',*:Tc'` to your `~/.tmux.conf`. See [Terminal configuration](</docs/en/terminal-config>) for other tmux settings -`CLAUDE_CODE_TOOL_MEMORY_LIMIT`| On Linux and WSL, set to a size such as `4G` to [cap the memory that Bash and PowerShell tool commands can use](</docs/en/tools-reference#memory-limit-on-linux-and-wsl>). Write the size in plain digits, alone for a number of bytes or with a `K`, `M`, `G`, or `T` suffix. Set `0` or `off` to turn the cap off. Once a tool command has turned the cap on or off, a changed value takes effect the next time you launch `claude`. Requires Claude Code v2.1.233 or later +`CLAUDE_CODE_TOOL_MEMORY_CGROUP_EXCLUDE`| On Linux and WSL, set to a comma-separated list of the kinds of processes Claude Code [excludes from the tool memory cap](</docs/en/tools-reference#memory-limit-on-linux-and-wsl>), such as `mcp` or `lsp`. Set `none` to cap every kind, or `all-new` to cap only Bash, PowerShell, and Monitor tool commands. Claude Code keeps Bash, PowerShell, and Monitor tool commands under the cap whatever you list. Requires Claude Code v2.1.246 or later +`CLAUDE_CODE_TOOL_MEMORY_LIMIT`| On Linux and WSL, set to a size such as `4G` to [cap the memory that Bash and PowerShell tool commands can use](</docs/en/tools-reference#memory-limit-on-linux-and-wsl>), and Monitor tool commands on v2.1.246 or later. Write the size in plain digits, alone for a number of bytes or with a `K`, `M`, `G`, or `T` suffix. Set `0` or `off` to turn the cap off. Once the first process Claude Code starts has turned the cap on or off, a changed value takes effect the next time you launch `claude`. Requires Claude Code v2.1.233 or later `CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS`| Deadline in milliseconds for dialogs Claude Code forwards to a remote client, such as a [Remote Control](</docs/en/remote-control>) or SDK host, and for the approval dialog for a [held cross-session message](</docs/en/cross-session-messaging#control-inbound-messages>), before Claude Code cancels them; permission prompts and `AskUserQuestion` questions use their own flows and aren’t governed by it. Also bounds the mid-session [Fable 5 usage-credits consent prompt](</docs/en/model-config#fable-5-and-usage-credits>) in a session that may be running unattended. [Control inbound messages](</docs/en/cross-session-messaging#control-inbound-messages>) and [non-interactive sessions](</docs/en/cross-session-messaging#non-interactive-sessions>) cover the full held-message expiry rules, including the cases where the deadline doesn’t apply. Overrides the [`dialogExpiry`](</docs/en/settings-reference#dialogexpiry>) setting; `0` or a negative value disables the deadline `CLAUDE_CODE_USE_ANTHROPIC_AWS`| Use [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) `CLAUDE_CODE_USE_BEDROCK`| Use [Amazon Bedrock](</docs/en/amazon-bedrock>) @@ -397,7 +399,7 @@ `DISABLE_UPDATES`| Set to `1` to block all updates including manual `claude update` and `claude install`. Stricter than `DISABLE_AUTOUPDATER`. Use when distributing Claude Code through your own channels and users should not self-update `DISABLE_UPGRADE_COMMAND`| Set to `1` to hide the `/upgrade` command `DO_NOT_TRACK`| Set to `1` to opt out of telemetry, with the same effect as `DISABLE_TELEMETRY`, including making [Remote Control](</docs/en/remote-control#requirements>) and the other features that need feature-flag fetching unavailable. Claude Code reads this variable as a standard boolean, so `0` leaves telemetry on, and honors it as the cross-tool convention recognized by many developer CLIs -`ENABLE_CLAUDEAI_MCP_SERVERS`| Set to `false` to disable [claude.ai MCP servers](</docs/en/mcp#use-mcp-servers-from-claude-ai>) in Claude Code. Enabled by default for logged-in users. To disable per-project or per-org, set [`disableClaudeAiConnectors`](</docs/en/settings-reference#disableclaudeaiconnectors>) in settings instead +`ENABLE_CLAUDEAI_MCP_SERVERS`| Set to `false` to stop Claude Code from fetching [claude.ai MCP servers](</docs/en/mcp#use-mcp-servers-from-claude-ai>). Enabled by default for logged-in users. To disable per-project or per-org, set [`disableClaudeAiConnectors`](</docs/en/settings-reference#disableclaudeaiconnectors>) in settings instead `ENABLE_PROMPT_CACHING_1H`| Set to `1` to request a 1-hour [prompt cache TTL](</docs/en/prompt-caching#cache-lifetime>) instead of the default 5 minutes. Intended for API key, [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) users. Subscription users within included usage receive the 1-hour TTL automatically on the [main conversation](</docs/en/prompt-caching#which-ttl-each-request-gets>). Subscription users drawing on [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) can set it to keep the 1-hour TTL. 1-hour cache writes are billed at a higher rate. To choose the TTL per request bucket instead, use `CLAUDE_CODE_PROMPT_CACHE_TTL` and `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, which take precedence over this variable `ENABLE_PROMPT_CACHING_1H_BEDROCK`| Deprecated. Use `ENABLE_PROMPT_CACHING_1H` instead `ENABLE_TOOL_SEARCH`| Controls [MCP tool search](</docs/en/mcp#scale-with-mcp-tool-search>). Unset, Claude Code defers all MCP tools by default. It still loads them upfront on Google Cloud’s Agent Platform models earlier than the Claude 4.5 generation, on a Microsoft Foundry deployment hosted on Azure, and when `ANTHROPIC_BASE_URL` points to a non-first-party host. `true` always defers and sends the beta header, except on those same Agent Platform models and Microsoft Foundry deployments; requests fail on proxies that don’t support `tool_reference`. `auto` loads upfront when tool definitions fit within 10% of context. `auto:N` sets a custom threshold, such as `auto:5` for 5%. `false` loads all tools upfront. A value you set yourself is ignored when `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` is set. Before v2.1.221, Claude Code disabled tool search for all models on Google Cloud’s Agent Platform unless you set this variable to `true` @@ -465,19 +467,16 @@ Features that need feature-flag fetching -Claude Code turns some features on through feature flags it fetches from Anthropic. You turn flag fetching off for a session by setting `DISABLE_GROWTHBOOK`, `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. Each variable’s row says which values do that. Claude Code also leaves fetching off when you connect through a [Claude apps gateway](</docs/en/claude-apps-gateway>). On Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry, Claude Code leaves fetching off unless a host platform that embeds Claude Code sets `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`. With fetching off, you can’t: - - * [Start sessions in auto mode by default](</docs/en/permission-modes#which-mode-a-session-starts-in>) on Pro, Max, and Team plans; Claude Code starts your sessions in Manual instead +Claude Code turns some features on through feature flags it fetches from Anthropic. You turn flag fetching off for a session by setting `DISABLE_GROWTHBOOK`, `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. Each variable’s row says which values do that. Claude Code also leaves fetching off when you connect through a [Claude apps gateway](</docs/en/claude-apps-gateway>), and on machines where a managed settings file, MDM profile, or policy helper requires gateway sign-in with [`forceLoginMethod: "gateway"`](</docs/en/settings-reference#forceloginmethod>), even before anyone signs in. On Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry, Claude Code leaves fetching off unless a host platform that embeds Claude Code sets `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`. With fetching off, you can’t: + + * [Start sessions in auto mode by default](</docs/en/permission-modes#which-mode-a-session-starts-in>) on Pro, Max, and Team plans * Have the VS Code extension [read settings files for the starting permission mode](</docs/en/permission-modes#switch-permission-modes>) * Run [`/auto-mode-setup`](</docs/en/auto-mode-config#generate-environment-entries>) to draft `autoMode.environment` entries * Use [Remote Control](</docs/en/remote-control#requirements>) - * Send or receive [cross-session messages](</docs/en/cross-session-messaging#availability>) * Run [`claude import` or the `/import` command](</docs/en/cli-reference#cli-commands>) * Create routines from the CLI with [`/schedule`](</docs/en/routines#troubleshooting>) * Use [the advisor tool](</docs/en/advisor#requirements>) - * Let [Claude choose the `/loop` interval](</docs/en/scheduled-tasks#let-claude-choose-the-interval>); Claude Code runs a `/loop` prompt with no interval on the fixed 10-minute schedule instead - * Run [the built-in `/loop` maintenance prompt](</docs/en/scheduled-tasks#run-the-built-in-maintenance-prompt>); Claude Code shows the usage message instead when you run `/loop` with no prompt - * Read or reply to [comments on an artifact](</docs/en/artifacts#collect-comments-on-an-artifact>), unless you set `CLAUDE_CODE_ARTIFACT_COMMENTS=1`; for Claude to reply to sent comments on its own, also set `CLAUDE_CODE_ARTIFACT_COMMENTS_AUTOREACT=1`. Neither override helps under `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, which [turns artifacts off entirely](</docs/en/artifacts#availability>) + * Read or reply to [comments on an artifact](</docs/en/artifacts#collect-comments-on-an-artifact>) * Have Claude Code refresh the [PR review status badge](</docs/en/interactive-mode#pr-review-status>) less often while you’re idle; Claude Code refreshes it every 60 seconds instead * Get the [v2 MCP client runtime](</docs/en/mcp#mcp-client-runtimes>) and its protocol probe without setting `MCP_SDK_GENERATION` and `MCP_PROTOCOL_NEGOTIATION`; Claude Code uses the v1 runtime unless you set `MCP_SDK_GENERATION=v2`, and skips the probe unless you set `MCP_PROTOCOL_NEGOTIATION=auto` * Get the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) by default for claude.ai and Console accounts on Windows with Git Bash installed; Claude Code routes shell commands through Git Bash unless you set `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. On Windows without Git Bash, the tool stays on
modified Error reference View current →
Show diff (466 lines)
--- a/errors.md +++ b/errors.md @@ -85,10 +85,9 @@ `Couldn't reconnect to your Remote Control session`| Network `N sessions ended while this machine was offline — the environment was cleaned up on the server and can't be resumed.`| Network `Couldn't share the transcript.`| Network -`Couldn't show context usage: the remote sent a reply this version can't display`| Network -`The remote session sent a reply this version can't display`| Network `Prompt is too long` / `Input is too long for requested model`| Request errors `Prompt is too long · automatic compaction failed:`| Request errors +`Prompt is too long · this conversation is a single exchange` / `A single-exchange conversation cannot be compacted`| Request errors `Context limit reached · /compact or /clear to continue`| Request errors `Context limit reached · /clear to continue`| Request errors `capability_rejected: prompt_too_long` on a Claude apps gateway session| Request errors @@ -103,6 +102,7 @@ `Unable to resize image`| Request errors `PDF too large` / `PDF is password protected`| Request errors `Extra inputs are not permitted`| Request errors +`API Error: 400 ... tools.N.custom.input_schema: JSON schema is invalid`| Request errors `There's an issue with the selected model`| Request errors `Model ... is not a recognized model id`| Request errors `Claude Opus is not available with the Claude Pro plan`| Request errors @@ -139,6 +139,8 @@ `Diff is too large for ultrareview` / `PR #<N> is too large for ultrareview`| Command-line errors `Could not find merge-base with <branch>`| Command-line errors `Your checkout has no branches (detached HEAD only)`| Command-line errors +`Ultrareview clones <owner>/<repo> in the cloud with the GitHub account connected to your Claude account, and none is connected`| Command-line errors +`Your connected GitHub account can't see <owner>/<repo>`| Command-line errors `Failed to resume the conversation`| Command-line errors `No conversation found with session ID: <session-id>`| Command-line errors `Cannot switch renderers in this session`| Command-line errors @@ -150,6 +152,8 @@ `Monitor "<name>" from plugin <plugin> references ${user_config.*} in its command`| Plugin errors `headersHelper for MCP server '<name>' references ${user_config.*}`| Plugin errors `Plugin archive integrity check failed`| Plugin errors +`Failed to load marketplace configuration`| Plugin errors +`Marketplace configuration file is corrupted`| Plugin errors `would be spawned with zero tools — refusing`| Tool errors `File is covered by a Read deny rule in your permission settings`| Tool errors `subagent_type is required: the general-purpose agent is not available in this session`| Tool errors @@ -161,16 +165,25 @@ `Too many messages to this session just now`| Tool errors `Refusing to send: reply target is a symlink` / `Refusing to send: cannot vet reply target`| Tool errors `Refusing to send: connected endpoint is not the expected process` / `Refusing to send: connected endpoint identity could not be read`| Tool errors +`Refusing to send: connected endpoint is not owned by this user` / `Refusing to send: connected endpoint owner could not be read`| Tool errors +`Refusing to send: connected endpoint is a different process with the expected pid`| Tool errors `Can't open MCP settings while no terminal is attached to this background session`| Background session errors `Can't open MCP settings in a background session`| Background session errors `blocked because the path is spelled in a form that cannot be safely resolved`| Background session errors `blocked because the path is network-shaped`| Background session errors `This session has no saved transcript`| Background session errors +`Can't open — this session is running in another terminal`| Background session errors +`This conversation is already open in another running Claude session`| Background session errors +`This session's saved conversation is no longer on disk`| Background session errors +`kept <id> — worktree has commits that are not pushed anywhere`| Background session errors `terminal host process died — press Enter to restart` / `This session's terminal host process died`| Background session errors `Session isn't responding` / `Press enter again to restart this session — it isn't responding`| Background session errors +`Session <id> was stopped while the respawn was in flight`| Background session errors `This session was running agent '<name>', which is no longer available`| Background session errors `CLAUDE_CODE_PROCESS_WRAPPER: launcher ...`| Background session errors `EUNKNOWN: unknown error, uv_spawn`| Background session errors +`EACCES: permission denied, posix_spawn`| Background session errors +`exited before it became reachable`| Background session errors `Claude Code process exited with code N`| Wrapper and IDE errors `Could not locate the Claude CLI on PATH`| Wrapper and IDE errors `Restored the code, but skipped N files`| Rewind warnings @@ -179,7 +192,9 @@ `Transcript saving is off — inherited CLAUDE_CODE_CHILD_SESSION marker`| Session saving warnings `Claude Code's fullscreen renderer didn't finish starting last time on this machine` / `Claude Code's fullscreen renderer has repeatedly failed to start on this machine`| Configuration warnings `Claude Code exited after an unrecoverable interface error (...)`| Configuration warnings +`Agent descriptions are over the 15.0k-token limit`| Configuration warnings `Ignoring N permissions.allow entries from ... this workspace has not been trusted`| Configuration warnings +`"crossSessionInbound" must be one of "accept", "hold", "refuse"`| Configuration warnings `headersHelper not run — this workspace has no persisted trust`| Configuration warnings `... is not matched by file permission checks`| Configuration warnings `... has a wildcard before the rest of the command`| Configuration warnings @@ -587,7 +602,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 doesn’t run before the first request. +The session reached the API client without any credential. [Background sessions](</docs/en/agent-view>) and cloud sessions show this message when the worker starts without a credential. Interactive, `-p`, and Agent SDK runs report the same condition as Not logged in and write this string only to their debug log, so if you found it there, follow that entry instead. 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 @@ -1053,10 +1068,11 @@ Connection to api.anthropic.com timed out after 10 seconds A proxy is configured via HTTPS_PROXY. Check that it allows connections to the host above. -Claude Code sends the check through the same [proxy configuration](</docs/en/network-config>) as API requests and gives each probe 10 seconds. When the failed probe went through a proxy, the message names the environment variable that configured it, such as `HTTPS_PROXY`. Before v2.1.222, the check used a different proxy transport with no timeout: behind a proxy URL with the `https://` scheme, it could stall on `Checking connectivity...` indefinitely and then fail even though API requests through the same proxy succeed. **What to do:** +Claude Code sends the check through the same [proxy configuration](</docs/en/network-config>) as API requests and gives each probe 10 seconds. When the failed probe went through a proxy, the message names the environment variable that configured it, such as `HTTPS_PROXY`. Before v2.1.222, the check used a different proxy transport with no timeout: behind a proxy URL with the `https://` scheme, it could stall on `Checking connectivity...` indefinitely and then fail even though API requests through the same proxy succeed. Claude Code skips this check when a [managed settings file, MDM policy, or policy helper](</docs/en/managed-settings>) sets [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>) to `"gateway"`, or sets [`forceLoginGatewayUrl`](</docs/en/settings-reference#forcelogingatewayurl>) without `forceLoginMethod`. With either configuration, Claude Code opens the sign-in step on the **Cloud gateway** screen rather than an Anthropic sign-in method. Claude Code also skips the check when a managed settings source on the machine exists but can’t be read, since that source may hold the gateway configuration. Before v2.1.247, Claude Code ran the check under this configuration too, and exited with this error when Anthropic’s endpoints were unreachable. **What to do:** * If the message names a proxy variable, check that its value points at the right proxy and ask your network team to allow HTTPS connections through it to the host in the message. See [Network configuration](</docs/en/network-config>). * Work through the checks in Unable to connect to API. The `curl` test and firewall guidance there apply to this check too. + * If your organization signs in through a [cloud gateway](</docs/en/claude-apps-gateway>) and this error appears on first run, update to Claude Code v2.1.247 or later. * If your network is open and the failure persists, Claude Code may not be [available in your country](<https://www.anthropic.com/supported-countries>) ### @@ -1242,23 +1258,6 @@ ​ -The remote sent a reply this version can’t display - -`/context` shows this line in a terminal [attached to a cloud session](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>): - - Couldn't show context usage: the remote sent a reply this version can't display - -While your terminal is attached, `/context` and `/btw` ask the cloud session for their answer. Sometimes the answer arrives in a form your terminal’s Claude Code can’t render. The usual cause is a version difference between the two. `/context` then shows the line above instead of the usage breakdown. `/btw` shows `The remote session sent a reply this version can't display` instead of its answer. The cloud session keeps running, and other commands still work. **What to do:** - - * Update Claude Code with `claude update`, reattach, and rerun the command - * If the line still appears, run `/feedback` and name the command - -Before v2.1.235, this case showed a raw JavaScript error instead, such as `undefined is not an object`. - -### - -​ - Couldn’t share the transcript After you agree to share your session transcript from a survey prompt, such as the [session quality survey](</docs/en/data-usage#session-quality-surveys>), Claude Code uploads it to Anthropic, or saves a local archive instead on third-party providers, on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, and when no Anthropic credentials are available. This message means the share didn’t complete. @@ -1296,13 +1295,25 @@ Context limit reached · /compact or /clear to continue · auto-compact is off · /config to turn it on -The **Auto-compact** toggle in `/config` writes `autoCompactEnabled` to user settings. The hint appears only when a `/config` change would take effect. For example, it doesn’t appear when [`DISABLE_AUTO_COMPACT`](</docs/en/env-vars>) or [`DISABLE_COMPACT`](</docs/en/env-vars>) turned auto-compact off. It also doesn’t appear when a higher-precedence scope, such as project or managed settings, set `autoCompactEnabled` to `false`. Nor does it appear in a terminal attached to a cloud session, where the cloud session owns auto-compact. Before v2.1.235, the line carried no auto-compact hint. Amazon Bedrock reports this condition as `Input is too long for requested model.`, which Claude Code handles the same way. Before v2.1.217, Claude Code didn’t recognize the Bedrock wording, so auto-compact never triggered on it and `/compact` failed with the same error. A [Claude apps gateway](</docs/en/claude-apps-gateway-config#upstream-error-messages>) reports this condition as `capability_rejected: prompt_too_long` when a cloud upstream rejects the request in the provider’s own error shape. Claude Code treats the token the same as `Prompt is too long`. Before v2.1.228, Claude Code didn’t recognize the token, so auto-compact didn’t trigger on it. When automatic compaction ran on this turn and failed on an underlying error, such as an unavailable model or an authentication failure, the message names that error after a separator: +The **Auto-compact** toggle in `/config` writes `autoCompactEnabled` to user settings. The hint appears only when a `/config` change would take effect. For example, it doesn’t appear when [`DISABLE_AUTO_COMPACT`](</docs/en/env-vars>) or [`DISABLE_COMPACT`](</docs/en/env-vars>) turned auto-compact off. It also doesn’t appear when a higher-precedence scope, such as project or managed settings, set `autoCompactEnabled` to `false`. Before v2.1.235, the line carried no auto-compact hint. Amazon Bedrock reports this condition as `Input is too long for requested model.`, which Claude Code handles the same way. Before v2.1.217, Claude Code didn’t recognize the Bedrock wording, so auto-compact never triggered on it and `/compact` failed with the same error. A [Claude apps gateway](</docs/en/claude-apps-gateway-config#upstream-error-messages>) reports this condition as `capability_rejected: prompt_too_long` when a cloud upstream rejects the request in the provider’s own error shape. Claude Code treats the token the same as `Prompt is too long`. Before v2.1.228, Claude Code didn’t recognize the token, so auto-compact didn’t trigger on it. When automatic compaction ran on this turn and failed on an underlying error, such as an unavailable model or an authentication failure, the message names that error after a separator: Prompt is too long · automatic compaction failed: <the underlying error> -Resolve the named error first; `/compact` fails on the same error until you do. Before v2.1.229, a failed automatic compaction surfaced `Prompt is too long` without the cause. **What to do:** - - * Run `/compact` to summarize earlier turns and free space, or `/clear` to start fresh +Resolve the named error first; `/compact` fails on the same error until you do. Before v2.1.229, a failed automatic compaction surfaced `Prompt is too long` without the cause. A single-exchange conversation has no earlier turns to summarize. When automatic compaction would have run on one, Claude Code skips the attempt and explains what fills the request instead. When the API doesn’t report token counts in its error, the message reads: + + Prompt is too long · this conversation is a single exchange and cannot be compacted — the request size comes mostly from system prompt, tool definitions, or attachments. + +When the API reports token counts in its error, Claude Code compares them with its own estimate of the conversation’s size to tell which is most of the request: the conversation’s own content, or the system prompt, tool definitions, and attachment content that Claude Code sends with it. When the conversation’s own content is most of the request, the message reads: + + Prompt is too long · the request is ~<request tokens> tokens (limit <limit>) and this conversation's own content is most of it. A single-exchange conversation cannot be compacted; start with less content (smaller files or pasted text). + +When most of the request is outside the conversation, the message reads: + + Prompt is too long · the request is ~<request tokens> tokens (limit <limit>) but this conversation is only ~<conversation tokens> tokens — the rest is system prompt, tool definitions, and attachment content. A single-exchange conversation cannot be compacted; reduce attached files/tools or start with less context. + +Before v2.1.162, Claude Code attempted the compaction anyway and surfaced the bare `Prompt is too long` when it failed. **What to do:** + + * In a multi-turn conversation, run `/compact` to summarize earlier turns and free space, or `/clear` to start fresh. A single-exchange conversation can’t be compacted, so shrink the request instead * Run `/context` to see a breakdown of what is consuming the window: system prompt, tools, memory files, and messages * Disable MCP servers you are not using with `/mcp disable <name>` to remove their tool definitions from context * Trim large `CLAUDE.md` memory files, or move instructions into [path-scoped rules](</docs/en/memory#path-specific-rules>) that load only when relevant @@ -1327,7 +1338,7 @@ Both forms name `/clear` instead of `/compact` when you have set [`DISABLE_COMPACT`](</docs/en/env-vars>). **What to do:** - * Run `/compact` to summarize earlier turns and free space, or `/clear` to start fresh + * In a multi-turn conversation, run `/compact` to summarize earlier turns and free space. To start fresh instead, run `/clear` * For more ways to reduce usage, see Prompt is too long Before v2.1.216, `/context` showed usage above 100% with no warning line explaining what that meant or how to recover. @@ -1437,6 +1448,22 @@ * 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. [Disable pre-release capabilities](</docs/en/llm-gateway-protocol#disable-pre-release-capabilities>) covers the exact scope. + +### + +​ + +Tool input schema is invalid + +A tool in the request declared an `input_schema` that fails the API’s JSON Schema validation, so the API rejected the whole request. The number after `tools.` is the failing tool’s position in the request’s tool list, not a name you can look up. + + API Error: 400 ... tools.N.custom.input_schema: JSON schema is invalid + +Claude Code [excludes MCP tools whose input schema would fail this validation](</docs/en/mcp#tools-with-invalid-input-schemas>) when it loads a server’s tools, so requests normally never include one. On a deployment that doesn’t receive the remote configuration that enables the exclusion, Claude Code records in the server’s log which tool would be rejected but sends it anyway, so this error can still occur. The error can also occur for a tool whose schema declares a JSON Schema dialect other than draft 2020-12 in `$schema`: Claude Code doesn’t check those schemas against the JSON Schema meta-schema, though it still excludes one with an invalid top-level property name. Before v2.1.216, no deployment ran the exclusion checks. **What to do:** + + * If your Claude Code version is earlier than v2.1.216, run `claude update`. + * Remove or [disable](</docs/en/mcp#disable-a-server-without-removing-it>) the MCP server that declares the invalid schema. The error names the tool only by position. On v2.1.216 or later, check each server’s log for a line naming a tool whose input schema would be rejected. If no log names one, disable servers one at a time. + * If you maintain the server, fix the tool’s `input_schema`. The schema must be valid JSON Schema, and top-level property names must be 1 to 64 characters long and use only ASCII letters and digits, `_`, `.`, and `-`. See [Tools with invalid input schemas](</docs/en/mcp#tools-with-invalid-input-schemas>). ### @@ -1949,6 +1976,40 @@ ​ +No GitHub account is connected to your Claude account + +You ran `/code-review ultra <PR#>` or `claude ultrareview <PR#>`, and before creating the cloud session Claude Code asks the server whether [the GitHub account connected to your Claude account](</docs/en/ultrareview#review-a-pull-request>) can reach the PR’s repository. No account is connected, or the connection expired, so the cloud clone would fail and Claude Code refuses the launch. Claude Code doesn’t spend a free run or bill usage credits for a refused launch. + + Ultrareview clones <owner>/<repo> in the cloud with the GitHub account connected to your Claude account, and none is connected (or the connection expired). To fix: run /web-setup to reuse your GitHub CLI login, or connect an account at https://claude.ai/code/onboarding?step=alt-auth — then re-run /code-review ultra 1234 (allow a minute after connecting). + +When [`/web-setup`](</docs/en/web-quickstart#connect-from-your-terminal>) isn’t available in your session, the message names only the claude.ai link. **What to do:** + + * Run `/web-setup` to connect your GitHub CLI login to your Claude account, or connect an account at [claude.ai/code/onboarding](<https://claude.ai/code/onboarding?step=alt-auth>) + * Rerun the review a minute after connecting + +Before v2.1.248, Claude Code didn’t check this before launch. + +### + +​ + +Your connected GitHub account can’t see the repository + +You ran `/code-review ultra <PR#>` or `claude ultrareview <PR#>`, and [the GitHub account connected to your Claude account](</docs/en/ultrareview#review-a-pull-request>) can’t read the PR’s repository, so the cloud clone would fail and Claude Code refuses the launch. Claude Code doesn’t spend a free run or bill usage credits for a refused launch. + + Your connected GitHub account can't see <owner>/<repo> — usually the Claude GitHub app isn't installed on <owner> or wasn't granted this repo (web-connected accounts need it for private repos), or a different GitHub account is connected. To fix: run /web-setup to reuse your GitHub CLI login, or install the app at https://github.com/apps/claude/installations/new — then re-run /code-review ultra 1234. + +When [`/web-setup`](</docs/en/web-quickstart#connect-from-your-terminal>) isn’t available in your session, the message names only the app install. **What to do:** + + * If your local `gh` CLI can read the repository, run `/web-setup` to connect that login to your Claude account + * Rerun the review after the change + +Before v2.1.248, Claude Code didn’t check this before launch. + +### + +​ + Failed to resume the conversation Claude Code couldn’t read or process the saved transcript for the session you selected from the [`claude --resume` picker](</docs/en/sessions#use-the-session-picker>), so it ends the process rather than continue in a partially loaded state. The message includes the command to retry: @@ -2102,6 +2163,26 @@ * If you publish the plugin, recompute the digest of the exact file the URL serves, for example with `shasum -a 256 my-plugin.zip`, or `Get-FileHash -Algorithm SHA256 my-plugin.zip` in PowerShell, and update the `sha256` in the marketplace entry * If you install the plugin, run `/plugin marketplace update <name>` to refresh the catalog in case the entry was corrected, then retry the install * If the digests still disagree after a refresh, ask the marketplace owner which file they pinned before installing + +### + +​ + +Failed to load marketplace configuration + +Claude Code keeps the plugin marketplaces you’ve added in a registry file at `~/.claude/plugins/known_marketplaces.json`. A plugin command that needs the registry, such as `claude plugin install`, fails with one of two messages when Claude Code can’t use the file: + + * `Failed to load marketplace configuration`: the file isn’t valid JSON, or can’t be read. An empty file fails this way too. + * `Marketplace configuration file is corrupted`: the file is valid JSON but its contents don’t match the registry schema. + +A missing file isn’t a failure: Claude Code treats it as a registry with no marketplaces. With an empty file, `claude plugin install` reports: + + ✘ Failed to install plugin "my-plugin": Failed to load marketplace configuration: JSON Parse error: Unexpected EOF + +Before v2.1.246, `claude plugin install` didn’t report this failure. **What to do:** + + * Open `~/.claude/plugins/known_marketplaces.json` and repair the JSON, or fix the entries the message names as not matching the registry schema + * If you can’t repair it, delete the file or replace its contents with `{}`, then re-add each marketplace with `claude plugin marketplace add <source>`. Claude Code re-registers the marketplaces your user or managed settings declare in [`extraKnownMarketplaces`](</docs/en/settings-reference#extraknownmarketplaces>) the next time you start it in a folder you’ve trusted. ## @@ -2271,6 +2352,9 @@ * `cannot vet reply target`: Claude Code couldn’t inspect the target path at all, for example because reading it failed with a permission error. * `connected endpoint is not the expected process`: the process holding the socket isn’t the session the message was addressed to, so the address is stale or another process replaced the socket. * `connected endpoint identity could not be read`: Claude Code connected but couldn’t read which process holds the other end, so it couldn’t confirm the target. This can be transient. + * `connected endpoint is not owned by this user`: the process holding the socket runs as a different user account, so it isn’t one of your sessions. + * `connected endpoint owner could not be read`: Claude Code connected but couldn’t read which user account owns the other end, so it couldn’t confirm the endpoint is yours. + * `connected endpoint is a different process with the expected pid`: the process id matches the one the message was addressed to, but Claude Code couldn’t confirm it’s the same process. Usually that session exited and the operating system reused its process id, so the address is stale. **What to do:** @@ -2278,6 +2362,9 @@ * Ask Claude to list your sessions again and resend; a refusal caused by a stale address clears once Claude sends to the current one * If `reply target is a symlink` repeats for one session, check what created a link at that session’s socket path, shown in its `/status` under `Peer address` * For `connected endpoint identity could not be read`, resend; the condition can be transient + * If `connected endpoint is not owned by this user` appears on a shared machine, the session at that address runs under another user’s account, so Claude can’t message it from yours + +Before v2.1.248, Claude Code didn’t check the endpoint’s owning user or process start time, so the refusals that name those checks don’t appear on earlier versions. ## @@ -2352,6 +2439,62 @@ ​ +This session is running in another terminal + +You opened a stopped session’s row in [agent view](</docs/en/agent-view>), and its saved conversation is already open in another live Claude Code process on this machine, so Claude Code refuses to start a second process that would write to the same transcript. Which message you see depends on [what holds the conversation](</docs/en/agent-view#opening-a-session-says-the-conversation-is-already-open>): + + Can't open — this session is running in another terminal + This conversation is already open in another running Claude session — use that one, or close it and try again + + * **`running in another terminal`** : a terminal holds the conversation, for example one where you resumed it with `claude --resume` or `/resume`. The row also shows `Open in a terminal`. + * **`already open in another running Claude session`** : another non-interactive Claude Code process holds it, for example a [background session](</docs/en/agent-view#the-supervisor-process>) process for the same conversation that hasn’t exited yet. + +Claude Code saves a reply you typed when opening the row and sends it as the session’s next prompt when the session next starts. **What to do:** + + * Continue the conversation in the process that has it open, or exit that process and open the row again + +Before v2.1.248, only the `already open in another running Claude session` refusal existed: a conversation resumed in a terminal didn’t count as open, and opening the row started a second Claude Code process writing to the same conversation. + +### + +​ + +This session’s saved conversation is no longer on disk + +You opened a [background session](</docs/en/agent-view>) that ended while the background service was off, and [transcript cleanup](</docs/en/settings-reference#cleanupperioddays>) has since removed its saved conversation, for example after the machine was off for weeks. Opening such a row normally [resumes its saved conversation](</docs/en/agent-view#sessions-show-as-failed-after-shutdown>). With nothing left to resume, Claude Code refuses rather than re-run the session’s original prompt without asking: + + This session's saved conversation is no longer on disk (it ended while the background service was off, and old transcripts are cleaned up), so there is nothing to resume. `claude rm 7c5dcf5d` deletes the row; `claude respawn 7c5dcf5d` runs its original prompt again instead. + +`claude attach <id>` prints this text. In agent view, the footer is shorter and ends with `ctrl+x deletes the row`. **What to do:** + + * Run `claude rm <id>` to delete the row. When one of the [kept cases](</docs/en/agent-view#what-deleting-a-session-removes>) applies, `claude rm` keeps the row and the worktree instead and names the reason + * To run the session’s original prompt again as a fresh conversation, run `claude respawn <id>` + +Before v2.1.248, opening such a row re-ran the session’s original prompt instead of refusing, pulling a weeks-old task back into the foreground. + +### + +​ + +Worktree has commits that are not pushed anywhere + +You tried to delete a [background session](</docs/en/agent-view#what-deleting-a-session-removes>) whose worktree holds commits Claude Code can’t confirm are saved elsewhere. Claude Code keeps the worktree and the session row rather than destroy the commits. `claude rm` prints the kept path and the reason: + + kept 7c5dcf5d — worktree has commits that are not pushed anywhere + worktree kept at /home/you/project/.claude/worktrees/fix-login + resolve that (commit/push, or remove the worktree), then run 'claude rm 7c5dcf5d' again + +When you delete from [agent view](</docs/en/agent-view>) with a `Ctrl+X` double-press, you consent to discarding uncommitted changes, but not to discarding commits, so Claude Code refuses there too. After a refused delete, the session’s row shows `not deleted` with the same reason. Commits on a remote don’t block the delete. Neither do commits on the local copy of your `origin` remote’s default branch, as long as that branch is checked out in your main checkout, the repository directory itself rather than a worktree. **What to do:** + + * Push the worktree’s branch, or merge it into the default branch checked out in your main checkout, then delete the session again + * To delete the session without pushing or merging the commits, first note the branch that `git worktree list` shows for the path the message names. Remove the worktree yourself with `git worktree remove --force <path>`, as described in [Clean up subagent and background-session worktrees](</docs/en/worktrees#clean-up-subagent-and-background-session-worktrees>), then run `claude rm <id>` again. Neither step deletes that branch, so the commits stay on it until you run `git branch -D <branch>`. + +Before v2.1.248, the default branch checked out in your main checkout didn’t count: a branch you had already merged there still triggered this refusal until its commits reached a remote. + +### + +​ + Terminal host process died Each [background session’s](</docs/en/agent-view>) terminal runs in a host process under the background service, and that process died while the service still held its connection, so the session couldn’t be reached. On Linux and WSL, the background service checks each host process every few seconds, marks the session failed when the process has exited but its connection to the service never closed, and shows the reason on its row in [agent view](</docs/en/agent-view#read-session-state>): @@ -2394,6 +2537,21 @@ ​ +Session was stopped while the respawn was in flight + +You opened a [background session](</docs/en/agent-view>) whose process wasn’t running, and while Claude Code was restarting it, another Claude Code process stopped it, for example `claude stop` in another terminal. Claude Code keeps the session stopped: + + Session <id> was stopped while the respawn was in flight + +Opening a session you just dispatched, while its process is still starting, waits for the process instead. Before v2.1.246, opening it at that moment could stop it and show this message. **What to do:** + + * If you didn’t stop the session, open its row again in agent view or run `claude respawn <id>` to restart it + * If you stopped it yourself, nothing remains to do: the session stays stopped + +### + +​ + Session agent no longer available You resumed a session that was running a [custom agent](</docs/en/sub-agents#invoke-subagents-explicitly>), started with `--agent` or the `agent` setting, and Claude Code didn’t find an agent by that name. It searches the session’s original directory first, when you have [trusted that workspace](</docs/en/permissions#project-allow-rules-and-workspace-trust>), then the directory you resume from. The session still resumes, but with the default tools and system prompt, so the agent’s tool restrictions no longer apply: @@ -2432,12 +2590,43 @@ Couldn't reach the background service (spawn background service: EUNKNOWN: unknown error, uv_spawn) — run 'claude daemon status' -On some accounts the message says `daemon` in place of `background service`. Claude Code starts the background service through PowerShell so the service survives closing the terminal, using PowerShell 7 when it’s installed and Windows PowerShell 5.1 otherwise. When neither PowerShell can run, Claude Code starts the service directly instead, so a policy that blocks only PowerShell doesn’t cause this error. If you see it, the policy is blocking the Claude Code executable itself. Before v2.1.212, Claude Code used only Windows PowerShell 5.1 to start the service, so any machine where Group Policy blocked PowerShell 5.1 failed with `Couldn't start the session — EUNKNOWN: unknown error, uv_spawn`, even with PowerShell 7 installed. **What to do:** +On some accounts the message says `daemon` in place of `background service`. On an npm installation, an `EUNKNOWN` that appears while `npm install -g @anthropic-ai/claude-code` is replacing the binary has the same cause as `EACCES` during a reinstall and clears when you retry after the install finishes. Claude Code starts the background service through PowerShell so the service survives closing the terminal, using PowerShell 7 when it’s installed and Windows PowerShell 5.1 otherwise. When neither PowerShell can run, Claude Code starts the service directly instead, so a policy that blocks only PowerShell doesn’t cause this error. If you see it while no npm install is running, the policy is blocking the Claude Code executable itself. Before v2.1.212, Claude Code used only Windows PowerShell 5.1 to start the service, so any machine where Group Policy blocked PowerShell 5.1 failed with `Couldn't start the session — EUNKNOWN: unknown error, uv_spawn`, even with PowerShell 7 installed. **What to do:** * If the message reads `Couldn't start the session`, upgrade to v2.1.212 or later. On earlier versions you can also run `claude daemon run` in a separate terminal first, then start the background session again. That command runs the background service in the terminal’s foreground, so the service lasts only as long as that terminal stays open. - * If the error appears on v2.1.212 or later, ask your Windows administrator to allow the Claude Code executable in the restriction policy + * If an npm install was replacing the binary, wait for it to finish, then start the background session again + * If the error appears on v2.1.212 or later while no npm install is running, ask your Windows administrator to allow the Claude Code executable in the restriction policy * If the background service stops when you close the terminal, Claude Code started it without PowerShell. Install PowerShell 7, or ask your administrator to unblock PowerShell, so the service can outlive the terminal. +### + +​ + +EACCES when starting a background session + +Claude Code couldn’t run its own binary to start the [background service](</docs/en/agent-view#the-supervisor-process>) that hosts background sessions. On an npm installation, this usually means `npm install -g @anthropic-ai/claude-code` was replacing the binary at that moment, whether you ran it or the [auto-updater](</docs/en/setup#auto-updates>) did. The error appears when you open a session from [agent view](</docs/en/agent-view>): + + Couldn't start the background service — spawn background service: EACCES: permission denied, posix_spawn '/usr/local/lib/node_modules/@anthropic-ai/claude-code/bin/claude' + +When you start a session with `/background` or `claude --bg`, the same reason appears inside `Couldn't reach the background service (...)`. During the same reinstall window the error can name another code instead, such as `ENOENT` or `ENOEXEC`, or `EUNKNOWN` or `EPERM` on Windows; an `EUNKNOWN` that persists across retries has a different cause. On an npm installation, Claude Code waits up to ten seconds for the reinstall to finish and retries on its own, so you see the error only when the binary stays unrunnable for longer, such as while npm is still downloading the package. Before v2.1.246, Claude Code failed at once. **What to do:** + + * Wait a few seconds, then open the session or dispatch again. + * If the error persists while no npm install is running, your user can’t run the installed binary. Check its permissions and its directory’s, or reinstall Claude Code. + +### + +​ + +Background service exited before it became reachable + +The process Claude Code started as the [background service](</docs/en/agent-view#the-supervisor-process>) exited before it accepted connections, so Claude Code couldn’t open your session. When the service printed an error before exiting, the reason in parentheses gives the exit code or signal and the first line the service printed, which names what stopped it: + + Couldn't reach the background service (background service exited before it became reachable (exit code N): <the service's first error line>) — run 'claude daemon status' + +When you open a session from [agent view](</docs/en/agent-view>), the same reason follows `Couldn't start the background service —`. When the service printed nothing before exiting, the message says `nothing on stderr` instead. Claude Code reports the failure with the service’s error line. Before v2.1.246, the failure surfaced only after a 45-second wait, as `background service did not become reachable within 45s`, without the service’s error line. **What to do:** + + * If the message quotes a line, fix what it names, then open the session or dispatch again. The next attempt starts the service again + * Run `claude daemon status` to check whether a service is running now + ## ​ @@ -2459,6 +2648,7 @@ **What to do:** * In VS Code, follow the **View output logs** link shown with the error to see the underlying failure + * In an Agent SDK application, catch the error around your message loop. The entries under [CLI process exit](</docs/en/agent-sdk/troubleshooting#cli-process-exit>) cover what your code receives in each SDK language. * Run `claude` in a terminal in the same project. The failure usually reproduces there with its real error message, which you can then look up on this page. * Run `claude doctor` in a terminal to check the installation and configuration @@ -2574,7 +2764,7 @@ Configuration warnings -Claude Code writes these messages to stderr rather than showing an error in the conversation, except where an entry notes that it writes the message to the debug log instead. It writes most of them at startup. Two exceptions: it writes the unrecognized-model diagnostic line at request time, and the unrecoverable interface error message as it exits. +Claude Code writes most of these messages to stderr, not into the conversation, and writes most of them at startup. An entry says so when its message appears somewhere else, such as in the debug log or as a startup notice in the conversation view, or at another time, such as the unrecognized-model diagnostic line at request time. ### @@ -2611,6 +2801,21 @@ * If the message names the fullscreen renderer, [Fullscreen rendering](</docs/en/fullscreen#fullscreen-renderer-didnt-finish-starting>) says what the next launch does, which depends on how you turned fullscreen on, and how to try fullscreen again or keep the classic renderer. Before v2.1.236, Claude Code exited without printing a message after this kind of error. + +### + +​ + +Agent descriptions are over the 15.0k-token limit + +Claude Code shows this warning as a startup notice in the conversation view rather than on stderr. The combined descriptions of your [subagents](</docs/en/sub-agents>), except the built-in ones, exceed 15,000 tokens as Claude Code estimates them. Each agent counts its name plus its `description` frontmatter. Claude Code loads every agent whether or not the total is over the limit, so the warning doesn’t change what loads. + + Agent descriptions are over the 15.0k-token limit (~16.2k tokens) · ask Claude to trim agent descriptions in .claude/agents/ + +**What to do:** + + * Shorten the `description` frontmatter of your agent files, or ask Claude to trim them for you. + * Remove agent files you no longer use. ### @@ -2687,6 +2892,23 @@ ​ +crossSessionInbound must be one of accept, hold, refuse + +A settings file sets [`crossSessionInbound`](</docs/en/settings-reference#crosssessioninbound>) to a value Claude Code doesn’t recognize, such as the typo `"reject"`. The warning’s second sentence depends on which file holds the value; in a user, project, local, or `--settings` file it reads: + + "crossSessionInbound" must be one of "accept", "hold", "refuse"; received "reject". This value was ignored; while it is present, cross-session messages are held for your approval instead of being delivered. Set it to one of the values above. + +In [managed settings](</docs/en/managed-settings>), Claude Code treats the unrecognized value as `refuse`, the most restrictive value, and the warning says cross-session messages are turned away until an administrator fixes it. For how the hold combines with values in your other settings files, see [`crossSessionInbound`](</docs/en/settings-reference#crosssessioninbound>). **What to do:** + + * Set the key to `"accept"`, `"hold"`, or `"refuse"`, or remove it + * When the warning names managed settings, ask the administrator to fix the value + +Before v2.1.248, Claude Code ignored an unrecognized value without warning. + +### + +​ + The 200K limit isn’t enforced You set [`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`](</docs/en/env-vars>), which normally makes [auto-compaction](</docs/en/model-config#default-auto-compact-thresholds>) hold sessions on 1M-context models to a 200K window, but no compaction threshold caps this session at or below 200K, so the conversation can grow past it.
modified Speed up responses with fast mode View current →
--- a/fast-mode.md +++ b/fast-mode.md @@ -64,7 +64,7 @@ You see fast mode spend in a different place depending on how you signed in, so first run [`/status`](</docs/en/commands>) to check. If it shows a `Login method` row such as `Claude Max account`, you signed in with a Claude subscription. If it shows an `API key` row instead, your requests bill to a Claude Console organization. * **Pro and Max** : you pay for fast mode from your usage credits. Go to [**Settings > Usage**](<https://claude.ai/settings/usage>) on claude.ai, where the **Usage credits** section shows how much you’ve spent in usage credits this month. That figure includes fast mode but doesn’t break it out separately. - * **Team and Enterprise** : your organization pays for your fast mode usage from its usage credits. For where your organization sees that spend, see [Claude for Teams and Enterprise](</docs/en/costs#claude-for-teams-and-enterprise>). + * **Team and Enterprise** : your organization pays for your fast mode usage from its usage credits. To see your own usage-credits spend, run [`/usage`](</docs/en/costs#check-your-usage-credits-spend>). For where your organization sees that spend, see [Claude for Teams and Enterprise](</docs/en/costs#claude-for-teams-and-enterprise>). * **Claude Console** : your organization pays for fast mode with the rest of its API usage. On the Console [Usage](<https://platform.claude.com/usage>) and [Cost](<https://platform.claude.com/cost>) pages, select **Speed (Research Preview)** in the **Group by** menu to separate fast mode from standard-speed usage. You see that option only when the selected date range includes fast mode usage. ##
modified Feature availability View current →
Show diff (110 lines)
--- a/feature-availability.md +++ b/feature-availability.md @@ -69,9 +69,8 @@ [Fast mode](</docs/en/fast-mode>)| ✓ ([Owner-enabled](</docs/en/fast-mode#enable-fast-mode-for-your-organization>) on Team and Enterprise)| ✓ (provisioned organizations)| ✗| ✗| ✗| ✗ [Auto mode](</docs/en/auto-mode-config>)| ✓| ✓| See note 2| ✓| See note 2| See note 2 [Advisor](</docs/en/advisor>)| ✓| ✓| ✗| ✗| ✗| ✗ -[Cross-session messaging](</docs/en/cross-session-messaging>)| ✓ 6| ✓ 6| ✗| ✗| ✗| ✗ +[Cross-session messaging](</docs/en/cross-session-messaging>)| ✓ 5| ✓ (same machine) 5| ✓ (same machine) 5| ✓ (same machine) 5| ✓ (same machine) 5| ✓ (same machine) 5 [Channels](</docs/en/channels>)| ✓| ✓| ✗| ✗| ✗| ✗ -[`/loop` scheduled tasks](</docs/en/scheduled-tasks>)| ✓| ✓| See note 3| See note 3| See note 3| See note 3 [GitHub Actions](</docs/en/github-actions>)| ✓| ✓| ✓| ✗| ✓| ✓ [GitLab CI/CD](</docs/en/gitlab-ci-cd>)| ✓| ✓| ✓| ✓| ✓| ✗ @@ -83,15 +82,14 @@ Organization-level controls and usage visibility. Feature| Claude subscription| Anthropic Console| Amazon Bedrock| Claude Platform on AWS| Google Cloud’s Agent Platform| Microsoft Foundry ---|---|---|---|---|---|--- -[Analytics dashboard and API](</docs/en/analytics>)| ✓ (dashboard: Team and Enterprise; API: Enterprise)| ✓ 5| ✗| ✗| ✗| ✗ +[Analytics dashboard and API](</docs/en/analytics>)| ✓ (dashboard: Team and Enterprise; API: Enterprise)| ✓ 4| ✗| ✗| ✗| ✗ [Server-managed settings](</docs/en/server-managed-settings>)| ✓ (Team and Enterprise)| ✓ (Team and Enterprise)| ✗| ✗| ✗| ✗ -[Zero Data Retention](</docs/en/zero-data-retention>)| ✓ (qualified Enterprise accounts)| ✓ (qualified accounts)| See note 4| ✓ (qualified accounts)| See note 4| See note 4 +[Zero Data Retention](</docs/en/zero-data-retention>)| ✓ (qualified Enterprise accounts)| ✓ (qualified accounts)| See note 3| ✓ (qualified accounts)| See note 3| See note 3 1 On Google Cloud’s Agent Platform, web search is available for Claude 4 models and later. 2 On these providers, auto mode supports only Claude Sonnet 5, Opus 4.7 or later, and Fable 5. See [Auto mode configuration](</docs/en/auto-mode-config>). The built-in starting permission mode on these providers is Manual. See [which mode a session starts in](</docs/en/permission-modes#which-mode-a-session-starts-in>). In v2.1.158 through v2.1.206, auto mode on these providers also required setting `CLAUDE_CODE_ENABLE_AUTO_MODE=1`; v2.1.207 removed the requirement. -3 Explicit intervals such as `/loop every 2 hours` work on every provider. On Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, and Microsoft Foundry, `/loop` cannot pick its own interval or supply the default maintenance prompt, so a prompt with no interval runs every 10 minutes, and `/loop` with no arguments shows the usage message. See [Scheduled tasks](</docs/en/scheduled-tasks>). -4 Subject to your agreement with the cloud provider. -5 Dashboard and API only. [Contribution metrics](</docs/en/analytics#enable-contribution-metrics>) requires a claude.ai Team or Enterprise organization. -6 Requires Claude Code v2.1.224 or later on macOS and Linux, including Linux inside WSL 2. On native Windows, requires Claude Code v2.1.234 or later. With API key authentication, same-machine messaging only. Claude can find your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions and your sessions on other machines only from a session that is connected to [Remote Control](</docs/en/remote-control>). Connecting needs a claude.ai sign-in and the other [Remote Control requirements](</docs/en/remote-control#requirements>). See [Message sessions on other machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>). +3 Subject to your agreement with the cloud provider. +4 Dashboard and API only. [Contribution metrics](</docs/en/analytics#enable-contribution-metrics>) requires a claude.ai Team or Enterprise organization. +5 Requires Claude Code v2.1.224 or later on macOS and Linux, including Linux inside WSL 2. On native Windows, requires Claude Code v2.1.234 or later. With API key authentication, messaging is same-machine only. On Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, and Microsoft Foundry, messaging is same-machine only and requires Claude Code v2.1.248 or later. Claude can find your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions and your sessions on other machines only from a session that is connected to [Remote Control](</docs/en/remote-control>). To connect, you need a claude.ai sign-in and the other [Remote Control requirements](</docs/en/remote-control#requirements>). See [Message sessions on other machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>). If you authenticate through an [LLM gateway](</docs/en/llm-gateway>), feature availability matches the underlying provider the gateway forwards to. Some Anthropic-only features such as the [Advisor](</docs/en/advisor>) work only if the gateway forwards requests intact to the Anthropic API. @@ -113,40 +111,40 @@ * Anthropic Console -**Not available:** all features that require a Claude subscription, plus [web search](</docs/en/tools-reference#websearch-tool-behavior>), [fast mode](</docs/en/fast-mode>), [Advisor](</docs/en/advisor>), [Channels](</docs/en/channels>), [cross-session messaging](</docs/en/cross-session-messaging>), the [analytics dashboard](</docs/en/analytics>), [server-managed settings](</docs/en/server-managed-settings>), and the [`/design-sync`, `/import`, and `/radio` commands](</docs/en/commands#all-commands>).**Partial support:** +**Not available:** all features that require a Claude subscription, plus [web search](</docs/en/tools-reference#websearch-tool-behavior>), [fast mode](</docs/en/fast-mode>), [Advisor](</docs/en/advisor>), [Channels](</docs/en/channels>), the [analytics dashboard](</docs/en/analytics>), [server-managed settings](</docs/en/server-managed-settings>), and the [`/design-sync`, `/import`, and `/radio` commands](</docs/en/commands#all-commands>).**Partial support:** * [Desktop](</docs/en/desktop>): only via [Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/overview>) * [Auto mode](</docs/en/auto-mode-config>): Sonnet 5, Opus 4.7 or later, and Fable 5 only - * [`/loop`](</docs/en/scheduled-tasks>): explicit intervals only + * [Cross-session messaging](</docs/en/cross-session-messaging>): between your sessions on this machine only 5 * [Zero Data Retention](</docs/en/zero-data-retention>): subject to your AWS agreement -**Alternatives:** for scheduling, use [`/loop`](</docs/en/scheduled-tasks>) with an explicit interval instead of `/schedule`. For cloud sessions, use [GitHub Actions](</docs/en/github-actions>) or [GitLab CI/CD](</docs/en/gitlab-ci-cd>). For web lookups, use the [WebFetch tool](</docs/en/tools-reference#webfetch-tool-behavior>) with a specific URL. +**Alternatives:** for scheduling, use [`/loop`](</docs/en/scheduled-tasks>) instead of `/schedule`. For cloud sessions, use [GitHub Actions](</docs/en/github-actions>) or [GitLab CI/CD](</docs/en/gitlab-ci-cd>). For web lookups, use the [WebFetch tool](</docs/en/tools-reference#webfetch-tool-behavior>) with a specific URL. -**Not available:** all features that require a Claude subscription, plus [fast mode](</docs/en/fast-mode>), [Advisor](</docs/en/advisor>), [Channels](</docs/en/channels>), [cross-session messaging](</docs/en/cross-session-messaging>), [GitHub Actions](</docs/en/github-actions>), the [analytics dashboard](</docs/en/analytics>), [server-managed settings](</docs/en/server-managed-settings>), and the [`/design-sync`, `/import`, and `/radio` commands](</docs/en/commands#all-commands>).**Available where Amazon Bedrock is not:** [web search](</docs/en/tools-reference#websearch-tool-behavior>).**Partial support:** +**Not available:** all features that require a Claude subscription, plus [fast mode](</docs/en/fast-mode>), [Advisor](</docs/en/advisor>), [Channels](</docs/en/channels>), [GitHub Actions](</docs/en/github-actions>), the [analytics dashboard](</docs/en/analytics>), [server-managed settings](</docs/en/server-managed-settings>), and the [`/design-sync`, `/import`, and `/radio` commands](</docs/en/commands#all-commands>).**Available where Amazon Bedrock is not:** [web search](</docs/en/tools-reference#websearch-tool-behavior>).**Partial support:** - * [`/loop`](</docs/en/scheduled-tasks>): explicit intervals only + * [Cross-session messaging](</docs/en/cross-session-messaging>): between your sessions on this machine only 5 -**Alternatives:** for scheduling, use [`/loop`](</docs/en/scheduled-tasks>) with an explicit interval instead of `/schedule`. For cloud sessions, use [GitLab CI/CD](</docs/en/gitlab-ci-cd>). +**Alternatives:** for scheduling, use [`/loop`](</docs/en/scheduled-tasks>) instead of `/schedule`. For cloud sessions, use [GitLab CI/CD](</docs/en/gitlab-ci-cd>). -**Not available:** all features that require a Claude subscription, plus [fast mode](</docs/en/fast-mode>), [Advisor](</docs/en/advisor>), [Channels](</docs/en/channels>), [cross-session messaging](</docs/en/cross-session-messaging>), the [analytics dashboard](</docs/en/analytics>), [server-managed settings](</docs/en/server-managed-settings>), and the [`/design-sync`, `/import`, and `/radio` commands](</docs/en/commands#all-commands>).**Partial support:** +**Not available:** all features that require a Claude subscription, plus [fast mode](</docs/en/fast-mode>), [Advisor](</docs/en/advisor>), [Channels](</docs/en/channels>), the [analytics dashboard](</docs/en/analytics>), [server-managed settings](</docs/en/server-managed-settings>), and the [`/design-sync`, `/import`, and `/radio` commands](</docs/en/commands#all-commands>).**Partial support:** * [Desktop](</docs/en/desktop>): via [managed settings](<https://claude.com/docs/third-party/claude-desktop/configuration>) or [Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/overview>) * [Web search](</docs/en/tools-reference#websearch-tool-behavior>): Claude 4 models and later * [Auto mode](</docs/en/auto-mode-config>): Sonnet 5, Opus 4.7 or later, and Fable 5 only - * [`/loop`](</docs/en/scheduled-tasks>): explicit intervals only + * [Cross-session messaging](</docs/en/cross-session-messaging>): between your sessions on this machine only 5 * [Zero Data Retention](</docs/en/zero-data-retention>): subject to your Google Cloud agreement -**Alternatives:** for scheduling, use [`/loop`](</docs/en/scheduled-tasks>) with an explicit interval instead of `/schedule`. For cloud sessions, use [GitHub Actions](</docs/en/github-actions>) or [GitLab CI/CD](</docs/en/gitlab-ci-cd>). +**Alternatives:** for scheduling, use [`/loop`](</docs/en/scheduled-tasks>) instead of `/schedule`. For cloud sessions, use [GitHub Actions](</docs/en/github-actions>) or [GitLab CI/CD](</docs/en/gitlab-ci-cd>). -**Not available:** all features that require a Claude subscription, plus [fast mode](</docs/en/fast-mode>), [Advisor](</docs/en/advisor>), [Channels](</docs/en/channels>), [cross-session messaging](</docs/en/cross-session-messaging>), [GitLab CI/CD](</docs/en/gitlab-ci-cd>), the [analytics dashboard](</docs/en/analytics>), [server-managed settings](</docs/en/server-managed-settings>), and the [`/design-sync`, `/import`, and `/radio` commands](</docs/en/commands#all-commands>).**Partial support:** +**Not available:** all features that require a Claude subscription, plus [fast mode](</docs/en/fast-mode>), [Advisor](</docs/en/advisor>), [Channels](</docs/en/channels>), [GitLab CI/CD](</docs/en/gitlab-ci-cd>), the [analytics dashboard](</docs/en/analytics>), [server-managed settings](</docs/en/server-managed-settings>), and the [`/design-sync`, `/import`, and `/radio` commands](</docs/en/commands#all-commands>).**Partial support:** * [Desktop](</docs/en/desktop>): only via [Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/overview>) * [Web search](</docs/en/tools-reference#websearch-tool-behavior>): [deployments hosted on Anthropic](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>) only * [Auto mode](</docs/en/auto-mode-config>): Sonnet 5, Opus 4.7 or later, and Fable 5 only - * [`/loop`](</docs/en/scheduled-tasks>): explicit intervals only + * [Cross-session messaging](</docs/en/cross-session-messaging>): between your sessions on this machine only 5 * [Zero Data Retention](</docs/en/zero-data-retention>): subject to your Azure agreement -**Alternatives:** for scheduling, use [`/loop`](</docs/en/scheduled-tasks>) with an explicit interval instead of `/schedule`. For cloud sessions, use [GitHub Actions](</docs/en/github-actions>). +**Alternatives:** for scheduling, use [`/loop`](</docs/en/scheduled-tasks>) instead of `/schedule`. For cloud sessions, use [GitHub Actions](</docs/en/github-actions>). **Not available:** all features that require a Claude subscription.Everything in CLI capabilities that vary by provider is available, except that [fast mode](</docs/en/fast-mode>) requires [provisioned access](</docs/en/fast-mode#enable-fast-mode-for-your-organization>). [Server-managed settings](</docs/en/server-managed-settings>) are also available when your API key belongs to a Team or Enterprise organization. @@ -160,7 +158,7 @@ Feature| Pro| Max| Team| Enterprise ---|---|---|---|--- -[Claude Code on the web](</docs/en/claude-code-on-the-web>)| ✓| ✓| ✓| ✓ 7 +[Claude Code on the web](</docs/en/claude-code-on-the-web>)| ✓| ✓| ✓| ✓ 6 [Routines](</docs/en/routines>)| ✓| ✓| ✓| ✓ [Remote Control](</docs/en/remote-control>)| ✓| ✓| Admin-enabled| Admin-enabled [Channels](</docs/en/channels>)| ✓| ✓| Admin-enabled| Admin-enabled @@ -174,10 +172,10 @@ [SSO](<https://support.claude.com/en/articles/9266767-what-is-the-team-plan>)| ✗| ✗| ✓| ✓ SCIM| ✗| ✗| ✗| ✓ [Compliance API](<https://platform.claude.com/docs/en/api/compliance>)| ✗| ✗| ✗| ✓ -[Zero Data Retention](</docs/en/zero-data-retention>)| ✗| ✗| ✗| ✓ 8 +[Zero Data Retention](</docs/en/zero-data-retention>)| ✗| ✗| ✗| ✓ 7 -7 On Enterprise, requires a premium seat or a Chat + Claude Code seat. See [Claude Code on the web](</docs/en/claude-code-on-the-web>). -8 Not included in the standard Enterprise plan. Requires separate enablement by Anthropic for qualified accounts. See [Zero Data Retention](</docs/en/zero-data-retention>). For pricing and the full plan comparison, see [Team plans](<https://support.claude.com/en/articles/9266767-what-is-the-team-plan>) and [Enterprise plans](<https://support.claude.com/en/articles/9797531-what-is-the-enterprise-plan>). +6 On Enterprise, requires a premium seat or a Chat + Claude Code seat. See [Claude Code on the web](</docs/en/claude-code-on-the-web>). +7 Not included in the standard Enterprise plan. Requires separate enablement by Anthropic for qualified accounts. See [Zero Data Retention](</docs/en/zero-data-retention>). For pricing and the full plan comparison, see [Team plans](<https://support.claude.com/en/articles/9266767-what-is-the-team-plan>) and [Enterprise plans](<https://support.claude.com/en/articles/9797531-what-is-the-enterprise-plan>). ##
modified Run Claude Code through a gateway View current →
--- a/gateways.md +++ b/gateways.md @@ -59,7 +59,8 @@ A gateway routes model API requests. A few things you might expect it to handle are configured elsewhere: * **Which model answers** : pick the model with the `/model` command or [model environment variables](</docs/en/model-config#setting-your-model>). The gateway decides where requests go, not which model the developer selects. Claude apps gateway can bound the choice with a per-group `availableModels` allowlist, but the developer still picks within it. - * **Other network traffic** : Claude Code itself sends version checks and downloads directly to Anthropic, separate from the gateway path. Whether the optional client telemetry stream is also on depends on your provider; the [telemetry defaults table](</docs/en/data-usage#telemetry-services>) covers each case. On a signed-in Claude apps gateway session, the gateway credential disables the Anthropic-bound analytics, and the [telemetry destination](</docs/en/claude-apps-gateway#whats-enforced-on-developers>) depends on how the session signed in. Your network still needs egress to the [required domains](</docs/en/network-config>), or set [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars>) to turn off the optional streams. + * **Other network traffic** : Claude Code itself sends version checks and downloads directly to Anthropic, separate from the gateway path. Your network still needs egress to the [required domains](</docs/en/network-config>), or set [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars>) to turn off the optional streams. + * **Client telemetry** : on a Claude apps gateway session, Claude Code sends no client analytics to Anthropic. It disables the Anthropic-bound analytics when the session signs in, and on machines where a managed settings file, an MDM profile, or a policy helper sets [`forceLoginMethod: "gateway"`](</docs/en/claude-apps-gateway-config#client-side-managed-settings>), it turns them off from startup, before anyone signs in. For other gateways, whether the optional client telemetry stream is on depends on your provider, and the [telemetry defaults table](</docs/en/data-usage#telemetry-services>) covers each case. Where a gateway session’s telemetry goes depends on how the session signed in, and [What’s enforced on developers](</docs/en/claude-apps-gateway#whats-enforced-on-developers>) says where each kind of session’s exports go. * **Corporate HTTP proxies** : an `HTTPS_PROXY` sits between Claude Code and every server it talks to, including the gateway. If your network requires one, [configure the proxy](</docs/en/network-config>) in addition to the gateway. For a Claude apps gateway you host, [sign-in checks that the proxy host is also on a private network](</docs/en/claude-apps-gateway#prerequisites>); if it isn’t, add the gateway host to `NO_PROXY` so the CLI connects to it directly. ##
modified Glossary View current →
--- a/glossary.md +++ b/glossary.md @@ -396,7 +396,7 @@ Subagent -A specialized AI assistant that runs in its own context window with a custom system prompt, specific tool access, and independent permissions. It works on a delegated task and returns a summary to the main conversation. Use subagents to keep large explorations out of your primary context or to run parallel research. Different from agent teams, where each agent is a full independent session you can talk to directly. Built-in subagents include Explore, Plan, and general-purpose. Learn more: [Create custom subagents](</docs/en/sub-agents>) +A specialized AI assistant that runs in its own context window with a custom system prompt, specific tool access, and independent permissions. It works on a delegated task and returns a summary to the main conversation. Use subagents to keep large explorations out of your primary context or to run parallel research. A subagent stays inside the session that spawned it. To pass findings between separate sessions you run yourself, use [cross-session messaging](</docs/en/cross-session-messaging>). Built-in subagents include Explore, Plan, and general-purpose. Learn more: [Create custom subagents](</docs/en/sub-agents>) ###
modified Automate actions with hooks View current →
--- a/hooks-guide.md +++ b/hooks-guide.md @@ -166,7 +166,7 @@ `auth_success`| Authentication completes `elicitation_dialog`| An MCP server opens an elicitation form and you haven’t typed for about six seconds `elicitation_url_dialog`| An MCP server asks you to open a browser URL and you haven’t typed for about six seconds -`elicitation_complete`| An MCP elicitation form is submitted or dismissed +`elicitation_complete`| An MCP server reports that a [URL-mode elicitation](</docs/en/hooks#elicitation-input>) is complete `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 `agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open @@ -405,7 +405,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 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`. +`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>) or by starting the session in [restricted mode](</docs/en/cli-reference#cli-flags>). It is never persisted as `defaultMode`. To switch the session to `acceptEdits`, your hook writes this JSON to stdout: @@ -558,7 +558,7 @@ The exit code determines what happens next: * **Exit 0** : the hook reports no objection through its exit code. 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, Claude Code adds stdout it [treats as plain text](</docs/en/hooks#exit-code-0>) to Claude’s context. - * **Exit 2** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart`, `Setup`, 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** : Claude Code blocks the action. Write a reason to stderr. Where it lands depends on the event: some events feed it to Claude as feedback so it can adjust, others show it to the user, and a few, such as `ConfigChange` and `Elicitation`, surface no message. Some events can’t be blocked: for `SessionStart` 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** : for most events, the outcome depends on what your hook printed to stdout: * A parsed object that passes schema validation: Claude Code ignores the exit code, the JSON alone decides the outcome, and the hook isn’t reported as an error. The per-event exceptions, like `WorktreeCreate` failing on any nonzero exit, are listed in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section. * A parsed object that fails schema validation: a non-blocking error; the notice carries the validation message. @@ -586,7 +586,7 @@ With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. These `permissionDecision` values are specific to `PreToolUse`: - * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) + * `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply, as do prompts for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) and for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code * `"deny"`: cancel the tool call and send the reason to Claude * `"ask"`: show the permission prompt to the user as normal @@ -891,7 +891,7 @@ Hooks and permission modes -`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. 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, and it can’t suppress the prompt for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) or MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>). Hooks can tighten restrictions but not loosen them past what permission rules allow. +`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](</docs/en/permission-modes>), including `dontAsk`. 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, and it can’t suppress the prompt for MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) or for connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. Hooks can tighten restrictions but not loosen them past what permission rules allow. ###
modified Hosting the Agent SDK View current →
--- a/hosting.md +++ b/hosting.md @@ -1,6 +1,4 @@ The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate. - -For security hardening beyond basic sandboxing, including network controls, credential management, and isolation options, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). ## @@ -127,8 +125,6 @@ asyncio.run(main()) -See [Session storage](</docs/en/agent-sdk/session-storage>) for the full `SessionStore` interface and reference adapters. - ### ​ @@ -268,7 +264,7 @@ Default SDK behavior reads settings and `CLAUDE.md` memory files from the filesystem. In a shared container that serves multiple tenants, those files can leak one tenant’s context into another tenant’s session. To isolate tenants inside a shared container: - * Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python so no filesystem settings load. + * Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python to skip user, project, and local settings. * Set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Auto memory](</docs/en/memory#auto-memory>) at `~/.claude/projects/<project>/memory/` loads into the system prompt regardless of `settingSources`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for the other inputs that load unconditionally. * Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config. When each config directory serves one working directory and you don’t share a [`SessionStore`](</docs/en/agent-sdk/session-storage>) across tenants, you can also set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) in `env` to keep the transcript paths under it short. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later. * Use a per-tenant working directory. Pass `cwd` explicitly on every `query()` call. @@ -324,8 +320,6 @@ asyncio.run(main()) -For per-tenant network controls, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). - ## ​ @@ -345,6 +339,18 @@ ​ +Troubleshoot deployment failures + +Use this section when an agent that works on your machine fails in a deployed service. Each item below names a failure and links the entry that covers it: + + * **CLI not found at service start** : in Python, a container or service manager runs your application with a different `PATH` than your shell, so an install that works locally isn’t visible to the process. In TypeScript, the image build skipped the SDK’s optional dependencies, or `pathToClaudeCodeExecutable` points at a file that doesn’t exist in the image. See [Claude Code not found](</docs/en/agent-sdk/troubleshooting#clinotfounderror-claude-code-not-found>). + * **CLI present in the image but won’t launch** : Claude Code can’t start from a binary that doesn’t match the container’s architecture or libc, or from a file that lost its execute permission in the image build. See [Failed to start Claude Code](</docs/en/agent-sdk/troubleshooting#cliconnectionerror-failed-to-start-claude-code>). + * **Claude Code process exits mid-run** : the error your application receives depends on the SDK language and on whether the CLI reported an error result first. The entries under [CLI process exit](</docs/en/agent-sdk/troubleshooting#cli-process-exit>) cover each message. + +## + +​ + Next steps * [Hosting cookbook](<https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb>): notebook walkthrough with [deployable code](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>) for Docker, Modal, and Kubernetes.
modified Interactive mode View current →
--- a/interactive-mode.md +++ b/interactive-mode.md @@ -164,7 +164,7 @@ Command| Action| From mode ---|---|--- -`Esc`| Enter NORMAL mode| INSERT, VISUAL +`Esc` or `Ctrl+[`| Enter NORMAL mode. In terminals that use the Kitty keyboard protocol, `Ctrl+[` requires v2.1.242 or later| INSERT, VISUAL `i`| Insert before cursor| NORMAL `I`| Insert at beginning of line| NORMAL `a`| Insert after cursor| NORMAL @@ -229,6 +229,7 @@ `dd`| Delete line `D`| Delete to end of line `dw`/`de`/`db`| Delete word/to end/back +`df{char}`/`dt{char}`| Delete to and including, or up to, the next occurrence of a character `cc`| Change line `C`| Change to end of line `cw`/`ce`/`cb`| Change word/to end/back @@ -397,7 +398,7 @@ When a queued entry reaches Claude depends on what you queued. - * Messages: if you queue a message while Claude is running tool calls, Claude Code passes it to Claude as soon as those tool calls finish, within the same turn. When the turn ends, Claude Code sends the messages that are still queued as the next turn, each as a separate message + * Messages: if you queue a message while Claude is running tool calls, Claude Code passes it to Claude as soon as those tool calls finish, within the same turn. When the turn ends with messages still queued, Claude Code sends only the oldest as the next turn. The rest stay queued and follow the same rule: Claude Code passes them to Claude when that turn’s tool calls finish, or sends the next oldest as the turn after * Commands and shell commands: Claude Code holds them until the turn ends, then runs them one at a time Press `Esc` to interrupt the turn instead. Claude Code keeps what you queued and sends it right away. @@ -432,7 +433,7 @@ In interactive mode, Claude Code leaves prompt suggestions off by default and hides the **Prompt suggestions** toggle in `/config` when it doesn’t evaluate feature flags. That happens in these cases: * You use Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry as the model provider, unless a host platform that embeds Claude Code sets [`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`](</docs/en/env-vars>) to a true value such as `1` - * You are signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>) + * You are signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>), or a managed settings file, MDM profile, or policy helper on your machine requires gateway sign-in with [`forceLoginMethod: "gateway"`](</docs/en/settings-reference#forceloginmethod>), even before you sign in * You set [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `DISABLE_GROWTHBOOK`](</docs/en/env-vars#features-that-need-feature-flag-fetching>) to a value that turns off feature-flag evaluation Outside those cases, if you start a session before Claude Code has ever fetched feature flags, such as your first session after installing on a slow network, Claude Code can also leave suggestions off and hide the **Prompt suggestions** toggle for that session. It shows them starting with the next session after a fetch succeeds. Claude Code also skips individual suggestions in several situations, including: @@ -602,7 +603,7 @@ `f`| Start a [forked subagent](</docs/en/sub-agents#fork-the-current-conversation>) that inherits the parent conversation plus this question and answer, so it can continue with full tool access. You stay in the current session and find the fork in the [panel below your prompt](</docs/en/sub-agents#observe-and-steer-running-forks>). Available in local sessions only `x`| Clear the list of earlier `/btw` exchanges shown above the current answer -`/btw` is the inverse of a [subagent](</docs/en/sub-agents>): it sees your full conversation but has no tools. Use `/btw` to ask about what Claude already knows from this session; use a subagent to go find out something new. +`/btw` sees your full conversation but has no tools. A [subagent](</docs/en/sub-agents>) has tools and starts from the prompt it receives, or, for a [fork](</docs/en/sub-agents#fork-the-current-conversation>), from a copy of this conversation. Use `/btw` to ask about what Claude already knows from this session; use a subagent to go find out something new. ##
modified Customize keyboard shortcuts View current →
--- a/keybindings.md +++ b/keybindings.md @@ -486,7 +486,7 @@ Write the key names of Ctrl shortcuts as Latin characters even when your active keyboard layout types other characters. How Claude Code matches the key you press to a binding depends on the kind of layout: - * Under a non-Latin layout such as Cyrillic, in a terminal that uses the Kitty keyboard protocol and reports the key’s US-layout position, Claude Code matches Ctrl shortcuts by that position, so with a Russian layout active, pressing Ctrl and the physical W key triggers `ctrl+w`. In a terminal that doesn’t report the position, Claude Code matches whatever the terminal sends for the keypress: an ASCII control code triggers the Latin shortcut, and a keypress that arrives as the Cyrillic character matches no binding + * Under a non-Latin layout such as Cyrillic, Claude Code matches Ctrl shortcuts by the key’s US-layout position when the terminal uses the Kitty keyboard protocol and reports that position. In such a terminal, with a Russian layout active, pressing Ctrl and the physical W key triggers `ctrl+w`. In a terminal that doesn’t report the position, Claude Code matches whatever the terminal sends for the keypress: an ASCII control code triggers the Latin shortcut, and a keypress that arrives as the Cyrillic character matches no binding * Under layouts that rearrange Latin letters, such as AZERTY, Claude Code matches the letter that the key types, so pressing Ctrl and the key labeled A triggers `ctrl+a` Before v2.1.247, pressing a Ctrl shortcut under a non-Latin layout didn’t trigger its binding in terminals that use the Kitty keyboard protocol, such as Ghostty, Kitty, WezTerm, and iTerm2. @@ -573,7 +573,7 @@ Ctrl+C| Hardcoded interrupt/cancel Ctrl+D| Hardcoded exit Ctrl+M| Claude Code always receives it as Enter -Ctrl+[| Claude Code always receives it as Escape +Ctrl+[| Claude Code always receives it as Escape. In terminals that use the Kitty keyboard protocol, this requires v2.1.242 or later Ctrl+I| Claude Code always receives it as Tab Ctrl+H| Sends the ASCII backspace byte. [How Claude Code reads it on Windows](</docs/en/terminal-config#fix-backspace-deleting-a-whole-word-on-windows>) depends on your terminal and the [`CLAUDE_CODE_BS_AS_CTRL_BACKSPACE`](</docs/en/env-vars>) environment variable Caps Lock| Not delivered to terminal applications
modified Set up Claude Code in a monorepo or large codebase View current →
--- a/large-codebases.md +++ b/large-codebases.md @@ -65,7 +65,7 @@ Repository root| Every file| Root only; subdirectory files load on demand when Claude reads there| Tasks span multiple packages or subsystems A subdirectory| That subtree only, until you grant more| That directory’s plus every ancestor’s| Work is scoped to one package or subsystem -Project settings in `.claude/settings.json` load only from your starting directory and are not inherited from parent directories the way CLAUDE.md files are: a `.claude/settings.json` at the repository root applies only when you start from the root. Each section below states whether its settings file belongs at the repository root or in the subdirectory you start from, and whether it is committed or kept local. +Project settings in `.claude/settings.json` aren’t inherited from parent directories the way CLAUDE.md files are. For which directory’s `.claude/settings.json` a session reads, see [where Claude Code looks for each file](</docs/en/settings#where-claude-code-looks-for-each-file>). Each section below states whether its settings file belongs at the repository root or in the subdirectory you start from, and whether it is committed or kept local. ## @@ -157,8 +157,8 @@ Claude’s content searches respect `.gitignore` by default, so paths already listed there, such as `node_modules/`, `dist/`, and `build/`, stay out of search results without additional configuration. For paths that are checked in, such as a vendored SDK or committed generated code, add `Read` deny rules in `permissions.deny` to block Claude from opening those files. The deny rules can cover everyone working in the repository, only you, or every session on the machine, depending on which settings file you put them in: - * **Everyone working in the repository** : commit the rules to `.claude/settings.json`. Like other project settings on this page, that file loads only from your starting directory, so place it at the repository root if you start Claude there, or in each package’s `.claude/` if you start from subdirectories. - * **Yourself only** : use `.claude/settings.local.json` at the repository root, which loads in every CLI session inside the repository regardless of starting directory, except in the cases where Claude Code [keeps the local file in the starting directory](</docs/en/settings#where-claude-code-looks-for-each-file>), such as on Windows. Relative patterns like the example’s `Read(./vendor/**)` still [anchor at the directory you start Claude Code from](</docs/en/permissions#read-and-edit>), so if you start sessions from subdirectories, write the rules in this file as `//`-absolute paths, such as `Read(//absolute/path/to/repo/vendor/**)`. Before v2.1.211, `.claude/settings.local.json` also loaded only from the starting directory. + * **Everyone working in the repository** : commit the rules to `.claude/settings.json`, at the repository root if you start Claude there, or in each package’s `.claude/` if you start from subdirectories. Like other project settings on this page, that file isn’t inherited from parent directories. + * **Yourself only** : use `.claude/settings.local.json` at the repository root, which loads in every CLI session inside the repository regardless of starting directory, except in the cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), such as on Windows. Relative patterns like the example’s `Read(./vendor/**)` still [anchor at the session’s current working directory](</docs/en/permissions#read-and-edit>) rather than the repository root, so if you start sessions from subdirectories, write the rules in this file as `//`-absolute paths, such as `Read(//absolute/path/to/repo/vendor/**)`. Before v2.1.211, `.claude/settings.local.json` also loaded only from the starting directory. * **Everyone, enforced in every session** : set the rules in [managed settings](</docs/en/managed-settings>), which user and project settings cannot override. The example below blocks build artifacts and a vendored SDK: @@ -367,7 +367,7 @@ Put it together -The combined configuration below uses the monorepo layout. The same files work for any subdirectory in a large single tree. Project settings load only from the directory you start Claude in, so each subdirectory’s `.claude/settings.json` must be self-contained rather than layered on a root file. The example commits `worktree`, `additionalDirectories`, and the `Read` deny rules in `.claude/settings.json` so every developer in `packages/api/` gets the same sibling access, sparse paths, and exclusions. The file below is the committed per-area settings for `packages/api/`: +The combined configuration below uses the monorepo layout. The same files work for any subdirectory in a large single tree. Each subdirectory’s `.claude/settings.json` must be self-contained rather than layered on a root file. The example commits `worktree`, `additionalDirectories`, and the `Read` deny rules in `.claude/settings.json` so every developer in `packages/api/` gets the same sibling access, sparse paths, and exclusions. The file below is the committed per-area settings for `packages/api/`: packages/api/.claude/settings.json
modified Connect Claude Code to an LLM gateway View current →
--- a/llm-gateway-connect.md +++ b/llm-gateway-connect.md @@ -360,7 +360,7 @@ Turn off traffic outside the gateway path -The gateway carries model requests, but Claude Code also sends nonessential background traffic outside the gateway path, to Anthropic and to third-party services such as GitHub: version checks, telemetry, error reports, release notes, and similar requests. On a network that only allows egress to the gateway, these requests fail and can appear as blocked connections in your egress monitoring. To turn that traffic off, set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` alongside the gateway variables, in the same shell exports or settings-file `env` block: +The gateway carries model requests, but Claude Code also sends nonessential background traffic outside the gateway path, to Anthropic and to third-party services such as GitHub: version checks, telemetry, release notes, and similar requests. On a network that only allows egress to the gateway, these requests fail and can appear as blocked connections in your egress monitoring. Claude Code attaches a credential to a telemetry or usage-metrics request only when the request goes to the host the credential belongs to. While `ANTHROPIC_BASE_URL` points at the gateway, Claude Code sends its telemetry events to Anthropic without your gateway credential. With a credential variable or `apiKeyHelper` also active, Claude Code doesn’t report usage metrics to the Console [analytics dashboard](</docs/en/analytics#access-analytics-for-api-customers>). Before v2.1.246, Claude Code could attach the gateway credential to telemetry and usage-metrics requests bound for Anthropic hosts; model requests always went to the gateway with the credential the gateway expects. To turn that traffic off, set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` alongside the gateway variables, in the same shell exports or settings-file `env` block: * Bash or Zsh
modified Control MCP server access for your organization View current →
Show diff (104 lines)
--- a/managed-mcp.md +++ b/managed-mcp.md @@ -1,4 +1,4 @@ -By default, anyone running Claude Code can connect any [MCP server](</docs/en/mcp>) they choose. Anthropic reviews connectors against its [listing criteria](<https://claude.com/docs/connectors/building/review-criteria>) before adding them to the [Anthropic Directory](<https://claude.ai/directory>), but doesn’t security-audit or manage any MCP server. As an administrator, you can restrict which servers run in your organization, from deploying a fixed approved set to disabling MCP entirely. This page covers how to: +By default, anyone running Claude Code can connect any [MCP server](</docs/en/mcp>) they choose. Anthropic reviews connectors against its [listing criteria](<https://claude.com/docs/connectors/building/review-criteria>) before adding them to the [Anthropic Directory](<https://claude.ai/directory>), but doesn’t security-audit or manage any MCP server. As an administrator, you can restrict which servers run in your organization, from deploying a fixed approved set to disabling MCP entirely. These restrictions cover the servers Claude Code loads itself, including the connectors it fetches from claude.ai. Connectors the desktop app delivers to its local and SSH sessions arrive in-process and are governed from your claude.ai organization settings instead; [How connectors reach Claude Code](</docs/en/mcp#how-connectors-reach-claude-code>) shows which controls apply to connectors in each kind of session, including cloud sessions. This page covers how to: * Choose a pattern that matches how much control you need * Deploy a fixed server set with `managed-mcp.json`, including how to disable MCP entirely @@ -18,10 +18,10 @@ Pattern| What it does| Configure ---|---|--- -**Disable MCP**| No servers load, apart from the VS Code extension’s own in-process server| `managed-mcp.json` with an empty server map +**Disable MCP**| No servers load, apart from in-process servers the app that started the session registers| `managed-mcp.json` with an empty server map **Fixed deployment**| Every user gets the same servers and can’t add others| `managed-mcp.json` with the servers you want **Approved catalog**| Publish a list of approved servers; users add the ones they want, anything else is blocked| `allowedMcpServers` \+ `allowManagedMcpServersOnly: true` -**Plugin servers only**| Servers can only come from plugins; users can’t add their own| [`strictPluginOnlyCustomization`](</docs/en/settings-reference#strictpluginonlycustomization>) with `mcp` in the list +**Plugin servers only**| Users can’t add servers through `~/.claude.json` or `.mcp.json`; plugin servers still load| [`strictPluginOnlyCustomization`](</docs/en/settings-reference#strictpluginonlycustomization>) with `mcp` in the list **Soft allowlist**| Enforce an allowlist that users can broaden in their own settings| `allowedMcpServers` without `allowManagedMcpServersOnly` **Denylist only**| Block known-bad servers, allow everything else| `deniedMcpServers` **No restrictions**| Users add anything| Don’t deploy any managed MCP configuration @@ -34,10 +34,10 @@ Exclusive control with managed-mcp.json -If you deploy a `managed-mcp.json` file, Claude Code loads only the servers that file defines, plus the VS Code extension’s own in-process server in sessions the extension starts. Users cannot add, modify, or use any other MCP servers, including plugin-provided servers and servers passed with the [`--mcp-config` CLI flag](</docs/en/cli-reference#cli-flags>). The file also suppresses claude.ai connectors unless you allow them alongside the managed set. What a user sees when a session does receive `--mcp-config` servers depends on where the session runs: +If you deploy a `managed-mcp.json` file, Claude Code loads only the servers that file defines, plus any in-process servers the app that started the session registers, such as the VS Code extension’s own server or the [connectors the desktop app delivers](</docs/en/mcp#how-connectors-reach-claude-code>). Users can’t add, modify, or use any other MCP servers, including plugin-provided servers and servers passed with the [`--mcp-config` CLI flag](</docs/en/cli-reference#cli-flags>). The file also suppresses the claude.ai connectors Claude Code fetches itself unless you allow them alongside the managed set. What a user sees when a session does receive `--mcp-config` servers depends on where the session runs: * On a workstation, Claude Code exits at startup with `You cannot dynamically configure MCP servers when an enterprise MCP config is present`. - * In [cloud sessions](</docs/en/claude-code-on-the-web>), which receive claude.ai connectors and other server-delivered servers through `--mcp-config`, Claude Code starts with the managed servers only. Nothing in the session tells the user which servers were left out. Claude Code names them in a warning on its stderr, which a [self-hosted runner](</docs/en/self-hosted-environments-configuration#mcp-servers>) records at the `debug` log level. Before v2.1.229, these sessions exited with the same error a workstation shows. + * In [cloud sessions](</docs/en/claude-code-on-the-web>) on a host where the file is deployed, such as a [self-hosted runner](</docs/en/self-hosted-environments-configuration#mcp-servers>), Claude Code starts with the managed servers only and skips the claude.ai connectors and other servers the cloud host delivers through `--mcp-config`. Nothing in the session tells the user which servers were left out. Claude Code names them in a warning on its stderr, which a self-hosted runner records at the `debug` log level. Before v2.1.229, these sessions exited with the same error a workstation shows. If a user passes `--strict-mcp-config`, Claude Code exits at startup on a workstation and in a cloud session alike, because that flag asks to replace the managed set. Two other settings can further filter the managed set: @@ -104,7 +104,7 @@ Disable MCP entirely -Deploy a `managed-mcp.json` containing an empty server map to block every MCP server apart from the VS Code extension’s own in-process server: +Deploy a `managed-mcp.json` containing an empty server map to block every MCP server apart from in-process servers the app that started the session registers: { "mcpServers": {} @@ -118,7 +118,7 @@ Allow claude.ai connectors alongside the managed set -Deploying `managed-mcp.json` suppresses [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) by default, including connectors an administrator configured for the organization in the claude.ai admin console. To load those connectors alongside the servers in `managed-mcp.json`, set `"allowAllClaudeAiMcps": true` in a [managed settings source](</docs/en/admin-setup#decide-how-settings-reach-devices>). Requires Claude Code v2.1.149 or later. With the setting enabled, Claude Code loads the same claude.ai connectors it would load if `managed-mcp.json` weren’t deployed. Allowlists and denylists still apply to those connectors, so you can block specific ones with `deniedMcpServers`. The setting affects only claude.ai connectors; plugin-provided servers stay suppressed. The setting also affects only the connectors Claude Code fetches itself. [Cloud sessions](</docs/en/claude-code-on-the-web>) receive connectors as server-delivered `--mcp-config` entries, and Claude Code suppresses those whenever `managed-mcp.json` is deployed, whether or not you set `allowAllClaudeAiMcps`. Claude Code reads this setting only from admin-controlled policy tiers: server-managed settings, an MDM-deployed plist or HKLM registry key, or a system `managed-settings.json` file. Placing it in user or project settings has no effect, so users cannot re-enable connectors that exclusive control suppressed. +By default, deploying `managed-mcp.json` suppresses the [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) Claude Code fetches itself, including connectors an administrator configured for the organization in the claude.ai admin console. To load those connectors alongside the servers in `managed-mcp.json`, set `"allowAllClaudeAiMcps": true` in a [managed settings source](</docs/en/admin-setup#decide-how-settings-reach-devices>). Requires Claude Code v2.1.149 or later. With the setting enabled, Claude Code loads the same claude.ai connectors it would load if `managed-mcp.json` weren’t deployed. Allowlists and denylists still apply to those connectors, so you can block specific ones with `deniedMcpServers`. The setting affects only the claude.ai connectors Claude Code fetches itself; plugin-provided servers stay suppressed. Cloud sessions and the desktop app’s local and SSH sessions receive connectors another way, described in [How connectors reach Claude Code](</docs/en/mcp#how-connectors-reach-claude-code>). A `managed-mcp.json` on the host that runs a cloud session, such as a [self-hosted runner host](</docs/en/self-hosted-environments-configuration#mcp-servers>), suppresses that session’s connectors whether or not you set `allowAllClaudeAiMcps`. No `managed-mcp.json` reaches the connectors the desktop app delivers to its local and SSH sessions. Claude Code reads `allowAllClaudeAiMcps` only from admin-controlled policy tiers: server-managed settings, an MDM-deployed plist or HKLM registry key, or a system `managed-settings.json` file. Placing it in user or project settings has no effect, so users cannot re-enable connectors that exclusive control suppressed. ## @@ -126,7 +126,7 @@ Policy-based control with allowlists and denylists -Allowlists and denylists filter which configured servers are allowed to load. They aren’t a registry: a server still has to be added by a user, a plugin, or `managed-mcp.json` before the allowlist or denylist applies to it. To deploy servers to users, use `managed-mcp.json`. Both lists also filter servers passed with the [`--mcp-config` CLI flag](</docs/en/cli-reference#cli-flags>); `--strict-mcp-config` limits which configuration files load and doesn’t bypass either list. To make the allowlist authoritative, set `allowedMcpServers` and `allowManagedMcpServersOnly: true` together in a [managed settings source](</docs/en/admin-setup#decide-how-settings-reach-devices>), such as server-managed settings or a deployed `managed-settings.json` file. Restrict the allowlist to managed settings only shows the configuration. Without `allowManagedMcpServersOnly`, allowlists from every settings scope merge, including a user’s own `~/.claude/settings.json`, so a user can broaden what your allowlist permits. Denylists merge from every scope regardless. +Allowlists and denylists filter which configured servers are allowed to load. They aren’t a registry: a server still has to be added by a user, a plugin, or `managed-mcp.json` before the allowlist or denylist applies to it. To deploy servers to users, use `managed-mcp.json`. Both lists also filter servers passed with the [`--mcp-config` CLI flag](</docs/en/cli-reference#cli-flags>), other than in-process `type: "sdk"` entries; `--strict-mcp-config` limits which configuration files load and doesn’t bypass either list. To make the allowlist authoritative, set `allowedMcpServers` and `allowManagedMcpServersOnly: true` together in a [managed settings source](</docs/en/admin-setup#decide-how-settings-reach-devices>), such as server-managed settings or a deployed `managed-settings.json` file. Restrict the allowlist to managed settings only shows the configuration. Without `allowManagedMcpServersOnly`, allowlists from every settings scope merge, including a user’s own `~/.claude/settings.json`, so a user can broaden what your allowlist permits. Denylists merge from every scope regardless. `allowManagedMcpServersOnly` is separate from `allowManagedPermissionRulesOnly`, which locks down [permission rules](</docs/en/permissions#managed-settings>) only. Setting that flag does not enforce the MCP allowlist. @@ -158,9 +158,9 @@ The `serverName` validation differs between the two lists: * In `deniedMcpServers`, `serverName` accepts any non-empty string, so you can block [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) by their display name. For example, `{ "serverName": "claude.ai Slack" }` blocks the Slack connector. Prefer a `serverUrl` entry when you need the deny to be robust to renames, or when a connector name collides and gains a ` (N)` suffix. - * In `allowedMcpServers`, `serverName` is limited to letters, numbers, hyphens, and underscores. Use `serverUrl` to allowlist a claude.ai connector. - -To turn off all claude.ai connectors, see [`disableClaudeAiConnectors`](</docs/en/mcp#disable-claude-ai-connectors>). + * In `allowedMcpServers`, `serverName` is limited to letters, numbers, hyphens, and underscores. Use `serverUrl` to allowlist a claude.ai connector Claude Code fetches itself; for connectors a cloud host delivers to self-hosted sessions, use the entries listed under [Connector traffic leaves your network](</docs/en/self-hosted-environments-deploy#connector-traffic-leaves-your-network>) instead. + +To turn off all the claude.ai connectors Claude Code fetches itself, see [`disableClaudeAiConnectors`](</docs/en/mcp#disable-claude-ai-connectors>). ### @@ -168,11 +168,11 @@ How a server is evaluated -Before loading a server, including one from `managed-mcp.json`, Claude Code runs three checks in order: - - 1. **Merge the lists.** Allowlist and denylist entries from every settings scope combine into one allowlist and one denylist, with the managed scope’s lists read from the one [managed source Claude Code selects](</docs/en/managed-settings#precedence-within-the-managed-tier>). When `allowManagedMcpServersOnly` is `true`, only the managed allowlist is kept; the denylist always merges from every scope. +Before loading a server, including one from `managed-mcp.json`, Claude Code runs the three checks below in order. In-process `type: "sdk"` servers, which the [app that started the session registers](</docs/en/mcp#how-connectors-reach-claude-code>), skip all three. + + 1. **Merge the lists.** Allowlist and denylist entries from every settings scope combine into one allowlist and one denylist, with the managed scope’s lists coming from the [managed source or sources Claude Code applies](</docs/en/managed-settings#how-claude-code-combines-managed-sources>). When `allowManagedMcpServersOnly` is `true`, only the managed allowlist is kept; the denylist always merges from every scope. 2. **Check the denylist.** A server that matches any denylist entry, by URL, command, or name, is blocked. Nothing overrides a denylist match. - 3. **Check the allowlist.** If `allowedMcpServers` isn’t set anywhere, every server that passed the denylist loads. If it is set, what the server must match depends on its type, shown in the table below. + 3. **Check the allowlist.** If `allowedMcpServers` isn’t set anywhere, every server that passed the denylist loads. If it is set, what the server must match depends on its type, shown in the table below. Built-in servers such as Claude in Chrome, the `ide` server Claude Code connects to in a running VS Code or JetBrains IDE, and servers the CLI itself configures skip this check. Server type| Allowed when it matches ---|--- @@ -372,10 +372,10 @@ Surface| What it controls| Where it lives| How to deliver ---|---|---|--- `managed-mcp.json`| Fixed server set, exclusive control| System path: `/Library/Application Support/ClaudeCode/`, `/etc/claude-code/`, or `C:\Program Files\ClaudeCode\`| MDM, GPO, fleet management, or any process with administrator privileges. Cannot be set through server-managed settings -`allowedMcpServers`| Allowlist of permitted servers| Any [settings scope](</docs/en/settings#where-settings-live>); Claude Code merges the lists from every scope unless `allowManagedMcpServersOnly` is set, and takes the managed scope’s list from the one [managed source it selects](</docs/en/managed-settings#precedence-within-the-managed-tier>)| For enforcement, a [managed settings source](</docs/en/admin-setup#decide-how-settings-reach-devices>): server-managed settings, `managed-settings.json`, MDM profile, or registry -`deniedMcpServers`| Denylist of blocked servers| Any settings scope; Claude Code merges the lists from every scope and takes the managed scope’s list from the one managed source it selects| Same as `allowedMcpServers` +`allowedMcpServers`| Allowlist of permitted servers| Any [settings scope](</docs/en/settings#where-settings-live>); Claude Code merges the lists from every scope unless `allowManagedMcpServersOnly` is set, and takes the managed scope’s list from the one [managed source it selects](</docs/en/managed-settings#precedence-within-the-managed-tier>) or [composes](</docs/en/managed-settings#compose-every-managed-source>)| For enforcement, a [managed settings source](</docs/en/admin-setup#decide-how-settings-reach-devices>): server-managed settings, `managed-settings.json`, MDM profile, or registry +`deniedMcpServers`| Denylist of blocked servers| Any settings scope; Claude Code merges the lists from every scope, and across managed sources as [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) describes| Same as `allowedMcpServers` `allowManagedMcpServersOnly`| Locks the allowlist to managed sources only| Managed settings sources only; the setting has no effect elsewhere| Same as `allowedMcpServers` -`allowAllClaudeAiMcps`| Loads the claude.ai connectors Claude Code fetches itself alongside `managed-mcp.json`. Connectors delivered to cloud sessions stay suppressed| Managed settings sources only; the setting has no effect elsewhere| Same as `allowedMcpServers` +`allowAllClaudeAiMcps`| Loads the claude.ai connectors Claude Code fetches itself alongside `managed-mcp.json`. A `managed-mcp.json` on the host that runs a cloud session still suppresses that session’s connectors| Managed settings sources only; the setting has no effect elsewhere| Same as `allowedMcpServers` ##
modified Deploy managed settings View current →
Show diff (200 lines)
--- a/managed-settings.md +++ b/managed-settings.md @@ -53,10 +53,10 @@ The file in the steps above is one of four ways to get managed settings onto a machine. Every mechanism carries the same policy keys as a `settings.json` file, so the [settings reference](</docs/en/settings-reference>) applies to all of them. A few keys are tied to particular sources, and each entry’s Scope line says which: - * **Delivery controls** : [`policyHelper`](</docs/en/settings-reference#policyhelper>) and [`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>) + * **Delivery controls** : [`policyHelper`](</docs/en/settings-reference#policyhelper>), [`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>), and [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) * **Gateway login keys** : [`forceLoginGatewayUrl`](</docs/en/settings-reference#forcelogingatewayurl>) and the `"gateway"` value of [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>) -A managed settings file, an MDM profile, or the claude.ai console applies one policy to everyone it reaches. To give one group of developers a different policy, deploy a different file or profile to that group; the claude.ai console [can’t target a group yet](</docs/en/server-managed-settings#current-limitations>), while a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) delivers managed settings per IdP group. When more than one mechanism delivers a policy to the same machine, Claude Code uses one and ignores the others; Which managed source Claude Code uses gives the order. The MDM and file rows are together called endpoint-managed settings, because the policy is stored on the developer’s device, as opposed to the server-managed row, where Claude Code fetches it. Pick a mechanism by how you already manage devices, using the table below. +A managed settings file, an MDM profile, or the claude.ai console applies one policy to everyone it reaches. To give one group of developers a different policy, deploy a different file or profile to that group; the claude.ai console [can’t target a group yet](</docs/en/server-managed-settings#current-limitations>), while a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) delivers managed settings per IdP group. When more than one mechanism delivers a policy to the same machine, Claude Code by default uses one and ignores the others. How Claude Code combines managed sources gives the order and the opt-in that applies every source. The MDM and file rows are together called endpoint-managed settings, because the policy is stored on the developer’s device, as opposed to the server-managed row, where Claude Code fetches it. Pick a mechanism by how you already manage devices, using the table below. Mechanism| How you deliver it| When Claude Code reads it| Use it when ---|---|---|--- @@ -75,8 +75,13 @@ A deployed policy reaches the developer’s sessions as follows: - * **Surfaces** : every surface that runs Claude Code on the machine reads these sources: the terminal, the VS Code and JetBrains extensions, the desktop app, and [Agent SDK](</docs/en/agent-sdk/typescript>) sessions, which load managed settings even when `settingSources` excludes the user, project, and local files. - * **Cloud sessions** : a session in an Anthropic-hosted environment doesn’t read a device’s MDM profile or file, so policy for it has to come from server-managed settings. A session in a [self-hosted environment](</docs/en/self-hosted-environments>) reads the managed settings file in its runner image only when server-managed settings deliver no keys, apart from the keys Claude Code reads from every admin source. + * **Surfaces** : on the developer’s machine, the terminal, the VS Code and JetBrains extensions, the desktop app’s Code tab, and [Agent SDK](</docs/en/agent-sdk/typescript>) sessions read all of these sources. Agent SDK sessions load managed settings even when `settingSources` excludes the user, project, and local files. + * **Cloud sessions** : a session in an Anthropic-hosted environment doesn’t read a device’s MDM profile or file, so policy for it has to come from server-managed settings. A session in a [self-hosted environment](</docs/en/self-hosted-environments>) also reads the managed settings file in its runner image, by default only when server-managed settings deliver no policy key, apart from the keys Claude Code reads from every admin source. How Claude Code combines managed sources covers the opt-in that applies both. + * **Cowork sessions** : [Cowork](<https://claude.com/docs/cowork/overview>) in the Claude Desktop app runs its sessions on Claude Code. In a Cowork session, Claude Code never fetches server-managed settings from the claude.ai admin console, even when the user signs in with a Team or Enterprise account, so which policy applies depends on where the session runs: + * **On the user’s machine** : by default, Claude Code in a Cowork session reads the MDM or OS-level policy and the managed settings file on that device, so deploy policy there. + * **In a full VM sandbox** : when your Claude Desktop managed configuration sets [`requireCoworkFullVmSandbox`](<https://claude.com/docs/third-party/claude-desktop/configuration#requirecoworkfullvmsandbox>), Claude Code runs inside a virtual machine where the device’s MDM policy and managed settings file aren’t present. + * **Remote Cowork sessions** : these run on Anthropic-managed VMs, where Claude Code has no device policy to read. +The [surface coverage](</docs/en/model-config#surface-coverage>) table compares Cowork with the other surfaces. * **Running sessions** : a session picks up most changes on the schedule in the table without a restart. Claude Code reads [`forceRemoteSettingsRefresh`](</docs/en/settings-reference#forceremotesettingsrefresh>) and [`requiredMinimumVersion`](</docs/en/settings-reference#requiredminimumversion>) only at session start, arms a new or changed [`policyHelper`](</docs/en/settings-reference#policyhelper>) entry at the next launch, and reads [some user-editable keys once at session start](</docs/en/settings#when-edits-take-effect>). * **Changes that need approval** : apart from the [updates that wait for the next launch](</docs/en/server-managed-settings#fetch-and-caching-behavior>), a server-managed change to a setting that [needs approval](</docs/en/server-managed-settings#security-approval-dialogs>), such as a hook or an `env` variable, waits for the developer to accept the dialog in an interactive session, and applies for the current run in a session an IDE extension or the Agent SDK hosts. Other server-managed changes apply on the next poll. * **Long-lived sessions** : a session left open for weeks can still lag a rollout. [`requiredMinimumVersion`](</docs/en/settings-reference#requiredminimumversion>) blocks an outdated binary from starting and doesn’t end a session that’s already running. @@ -114,11 +119,16 @@ ​ -Which managed source Claude Code uses - -When your organization delivers more than one managed source, Claude Code uses the first of these sources that delivers at least one policy key and ignores the rest rather than merging them, apart from the few cross-source keys covered in Keys read from every admin source. Claude Code shows no warning for the sources it skips. To see which source it used, run `/status`. Two terms recur in this section: - - * **Policy key** : any settings key other than the control key [`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>). A managed settings file or MDM policy that contains only that key doesn’t count, and Claude Code moves on to the next source. +How Claude Code combines managed sources + +When your organization delivers more than one managed source to the same machine, the [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) key decides what Claude Code does with the others: + + * **`"first-wins"`, the default**: Claude Code uses the highest-ranked source that delivers at least one policy key and ignores the rest rather than merging them, apart from the few keys in Keys read from every admin source. Claude Code shows no warning for the sources it skips; `/status` names the source it used and the ones it skipped. + * **`"merge"`** : Claude Code applies every admin source that delivers a policy key and combines them by kind of key: on most keys the higher-ranked source’s value applies, lists union, and locks take the strictest value. Compose every managed source says where to set the key and how each kind of key combines. Requires Claude Code v2.1.242 or later. + +Both settings rank the sources the same way. Two terms recur in this section: + + * **Policy key** : any settings key other than the two control keys, [`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>) and [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>). A managed settings file or MDM policy that contains only those doesn’t count, and Claude Code moves on to the next source. * **Admin source** : one of the first three sources below. The HKCU registry is user-writable and isn’t one. Claude Code checks the sources in this order, highest priority first: @@ -128,7 +138,7 @@ 3. Managed settings files, `managed-settings.d/*.json` and `managed-settings.json` merged together 4. The HKCU registry, on Windows, and on WSL once the HKLM registry or the Windows managed settings file turns [`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>) on and the HKCU value also sets it. Claude Code reads it only when no source above it delivers a policy key and no host-supplied parent settings supply a restrictive key -This diagram shows the ranking, with examples of the cross-source keys Claude Code reads from the first three sources: +This diagram shows the ranking, with examples of the cross-source keys Claude Code reads from the first three sources under either setting: ### @@ -136,14 +146,15 @@ Keys read from every admin source -For most keys, Claude Code reads only the source it selected. A value in a lower-ranked source is ignored even when the selected source leaves that key unset. A few keys work differently. Claude Code reads them from every admin source, so a lower-ranked MDM policy or managed settings file can still set them when the selected source doesn’t. Claude Code leaves the user-writable HKCU registry out of that scan; when HKCU is the only source and no host supplies parent settings, HKCU applies like any selected source. The cross-source keys include: - - * `sandbox.network.allowManagedDomainsOnly` and `sandbox.filesystem.allowManagedReadPathsOnly`: a `true` in any admin source turns the lock on. While a lock is on, Claude Code unions the allowlist it locks, `sandbox.network.allowedDomains` together with `WebFetch(domain:...)` allow rules, or `sandbox.filesystem.allowRead`, across every admin source. Without the lock, an unselected admin source’s allowlist is ignored like any other key from an unselected source +Under the default `"first-wins"` setting, Claude Code reads most keys only from the source it selected, and ignores a value in a lower-ranked source even when the selected source leaves that key unset. A few keys work differently. Claude Code reads them from every admin source, so a lower-ranked MDM policy or managed settings file can still set them when the selected source doesn’t. Claude Code leaves the user-writable HKCU registry out of that scan; when HKCU is the only source and no host supplies parent settings, HKCU applies like any selected source. The cross-source keys include: + + * `sandbox.network.allowManagedDomainsOnly` and `sandbox.filesystem.allowManagedReadPathsOnly`: a `true` in any admin source turns the lock on. While a lock is on, Claude Code unions the allowlist it locks, `sandbox.network.allowedDomains` together with `WebFetch(domain:...)` allow rules, or `sandbox.filesystem.allowRead`, across every admin source. Without the lock, Claude Code treats the allowlist like any other key, so under `"first-wins"` an unselected admin source’s allowlist is ignored * `allowAllClaudeAiMcps` * The sandbox binary paths `sandbox.bwrapPath` and `sandbox.socatPath` * The sandbox `ripgrep` binary, [`sandbox.ripgrep`](</docs/en/settings-reference#sandbox-ripgrep>) * `sandbox.filesystem.disabled` and `sandbox.network.strictAllowlist` * [`useAutoModeDuringPlan`](</docs/en/settings-reference#useautomodeduringplan>) and [`syncClaudeAiSkills`](</docs/en/settings-reference#syncclaudeaiskills>), where a `false` from any admin source turns the behavior off. A `false` in the developer’s user or local settings turns it off too; each key can only deny + * [`enableArtifact`](</docs/en/settings-reference#enableartifact>), where a `false` from any admin source turns the [Artifact tool](</docs/en/artifacts>) off. A `false` in the developer’s user, project, or local settings turns it off too, and no source turns it back on; see [which lower-level values still count](</docs/en/settings#exceptions-to-managed-settings-precedence>). Requires Claude Code v2.1.242 or later * A commit-trailer opt-out in `attribution`, or in the deprecated `includeCoAuthoredBy`, from any tier * [`forceRemoteSettingsRefresh`](</docs/en/server-managed-settings>) * `env`, merged per variable across the admin sources: each variable comes from the highest-priority source that defines it, so lower sources fill in variables the higher ones leave unset. A few variables follow their own rules; [Per-key exceptions across managed sources](</docs/en/server-managed-settings#per-key-exceptions-across-managed-sources>) names each one. Requires Claude Code v2.1.223 or later. Before v2.1.223, Claude Code applied the selected source’s whole `env` block only @@ -152,6 +163,25 @@ ​ +Compose every managed source + +To have Claude Code apply every admin source your organization delivers, set [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) to `"merge"` in the highest-ranked source you deploy. Claude Code reads the key only from the highest-ranked source that carries either the key or a policy key, so a lower source can’t opt itself into merging with the source above it, and a machine that never receives server-managed settings needs the key in its MDM profile too. The user-writable HKCU registry never merges with another source. Requires Claude Code v2.1.242 or later. Under `"merge"`, Claude Code adds a lower source’s list entries, such as `permissions.allow` rules and hooks, to the policy, so turn it on only when every source ranked below your highest one is under an administrator’s control. This table shows how Claude Code combines each kind of key under `"merge"`; the [`managedSourcesBehavior` entry](</docs/en/settings-reference#managedsourcesbehavior>) names every key in the restriction allowlist and highest-source-only rows. + +Kind of key| How Claude Code combines it| Examples +---|---|--- +Lists| Combines the entries from every source| `permissions.allow`, `hooks`, `sandbox.network.allowedDomains`, `deniedMcpServers` +Locks| Applies the strictest value any source sets; a looser value applies only from the highest-ranked source| `allowManagedHooksOnly`, `permissions.disableBypassPermissionsMode`, `crossSessionInbound` +Restriction allowlists| Takes the list whole from the highest-ranked source that sets it, without adding entries from lower sources| `availableModels`, `allowedMcpServers`, `strictKnownMarketplaces`, `allowedChannelPlugins`, and the `fallbackModel` chain +Keys read from the highest-ranked source only| Ignores the key in every lower source, even when the highest-ranked source leaves it unset| Credential helpers such as `apiKeyHelper`, login pins such as `forceLoginOrgUUID`, `modelPicker`, `permissions.defaultMode` +`env`| Merges per variable across admin sources under either setting, as Keys read from every admin source describes| +Every other key| Takes the value from the highest-ranked source that sets it| `model`, `cleanupPeriodDays` + +To confirm which sources combined on a machine, read the `Setting sources` line in `/status`; that section says what each label means. + +### + +​ + Compute the policy with a helper program A [`policyHelper`](</docs/en/settings-reference#policyhelper>) is an executable your MDM policy or managed settings file names, and Claude Code runs it to compute managed settings at startup. When the selected source configures one and the helper emits a `managedSettings` object, that output changes what Claude Code reads: @@ -168,9 +198,30 @@ When another application launches Claude Code, such as Claude Desktop, an IDE extension, or an Agent SDK app, that host can pass its own managed settings through the SDK `managedSettings` option. Claude Code calls these parent settings. By default, Claude Code ignores parent settings whenever an admin source is present: server-managed settings, an MDM or OS-level policy, or a managed settings file. To have Claude Code merge parent settings alongside an admin source, set [`parentSettingsBehavior`](</docs/en/settings-reference#parentsettingsbehavior>) to `"merge"` in the highest-priority managed source; Claude Code reads the key from that source only. Claude Code then keeps only the host’s values that restrict what Claude can do, with one gap to know about: unless you also set the `allowManaged*Only` locks, the host’s permission allow rules and sandbox allowlists still apply. See [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>) for the locks. A [`policyHelper`](</docs/en/settings-reference#policyhelper>) can turn parent merging off regardless of this key; its entry says when. Claude Code also applies these checks to parent-supplied values on their own: - * When any admin source sets `allowManagedPermissionRulesOnly`, Claude Code drops [parent-supplied](</docs/en/claude-apps-gateway#restrict-parent-settings>) permission allow rules and `additionalDirectories` as it reads them, even when a higher-priority source leaves the key unset. The key’s effect on your own permission rules still comes only from the selected source, or from parent settings you’ve chosen to merge - * A `forceLoginOrgUUID` or `allowedMcpServers` value in the highest-priority admin source blocks a parent-supplied one, and Claude Code enforces the admin value. A value in an admin source that isn’t the highest-priority one neither applies nor blocks the parent’s. Before v2.1.223, a value in any admin source blocked the parent’s - * An `availableModels` value follows the same rule as `forceLoginOrgUUID` and `allowedMcpServers` + * When any admin source sets `allowManagedPermissionRulesOnly`, Claude Code drops [parent-supplied](</docs/en/claude-apps-gateway#restrict-parent-settings>) permission allow rules and `additionalDirectories` as it reads them, even when a higher-priority source leaves the key unset. The key’s effect on your own permission rules comes from the managed settings Claude Code applies, or from parent settings you’ve chosen to merge + * Claude Code enforces the `forceLoginOrgUUID` or `allowedMcpServers` value in the managed settings it applies and blocks a parent-supplied one. A value in a lower admin source that Claude Code doesn’t apply neither applies nor blocks the parent’s. The [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) entry says which source supplies each key under `"merge"`. Before v2.1.223, a value in any admin source blocked the parent’s + * An `availableModels` value follows the same rule as `allowedMcpServers` + +#### + +​ + +Keep Cowork folder access when only managed rules apply + +[Cowork](<https://claude.com/docs/cowork/overview>) in the Claude Desktop app runs its sessions on Claude Code and grants each session access to its working folders, such as the folder the user connects, through allow rules it supplies when it launches the session. When your managed policy sets [`allowManagedPermissionRulesOnly`](</docs/en/settings-reference#allowmanagedpermissionrulesonly>), Claude Code keeps only the allow rules in the managed policy: it drops allow rules a host supplies as parent settings, as `--allowedTools`, or in a settings file, so writes to those folders lose their pre-approval. In a Cowork session that asks before edits, Cowork can’t show the prompt, and Claude reports each write as blocked because the path resolves to a protected location or a path outside the connected folder. To restore the writes, add allow rules for those folders to the managed source Claude Code selects on those machines: on an MDM-managed fleet, that’s the MDM policy rather than a separate managed settings file. This example uses the file form, and an MDM policy takes the same keys. It keeps `allowManagedPermissionRulesOnly` set and allows edits under a `CoworkProjects` folder in each user’s home directory; replace the path with the folders your users connect: + +managed-settings.json + + { + "allowManagedPermissionRulesOnly": true, + "permissions": { + "allow": [ + "Edit(~/CoworkProjects/**)" + ] + } + } + +After you deploy the policy, Claude can save files under that folder in a new Cowork session. [Read and Edit rules](</docs/en/permissions#read-and-edit>) cover the path syntax, including the `//` form for absolute paths. ### @@ -204,14 +255,15 @@ * `(remote)`: server-managed settings from claude.ai or a gateway * `(plist)` or `(HKLM)`: an MDM or OS policy * `(file)`, `(drop-ins)`, or `(file + drop-ins)`: `managed-settings.json`, the drop-in directory, or both + * `(remote + file, merged)`, or another list ending in `, merged`: your organization composes every managed source, and Claude Code merged the listed sources into the policy. A lower source can still supply `env` variables without appearing in the list. Requires Claude Code v2.1.242 or later * `(HKCU)`: the user-writable registry fallback * `(parent process)`: an embedding host supplied restrictive settings * `(helper)`: a [`policyHelper`](</docs/en/settings-reference#policyhelper>) configured by the selected MDM or file source -When the policy isn’t applying, the line tells you which of two problems you have: - - * **The line is missing** : Claude Code found no managed source that delivers a policy key. Check that the file sits at the path for the OS, that it’s valid JSON, and that it contains a key other than `wslInheritsWindowsSettings`. - * **The line names a source other than the one you deployed** : a higher-priority source is present and Claude Code ignored yours. Which managed source Claude Code uses gives the order. +When Claude Code found a managed source on the machine and didn’t select it, a second line, `Skipped sources`, names each such source. Read it to distinguish a policy that never reached the machine from one that reached it and that a higher-priority source overrode. Requires Claude Code v2.1.242 or later. When the policy isn’t applying, the `Setting sources` line tells you which of two problems you have: + + * **The line is missing** : Claude Code found no managed source that delivers a policy key. If you deployed a managed settings file, check that it sits at the path for the OS, that it’s valid JSON, and that it contains a policy key rather than only the control keys. + * **The line names a source other than the one you deployed** : a higher-priority source is present and Claude Code ignored yours, and `Skipped sources` lists it. How Claude Code combines managed sources gives the order. ### @@ -242,6 +294,7 @@ `availableModels`| Enforced as an empty allowlist until fixed, so only the Default model is available; a non-string entry is stripped and the valid subset enforced. `enforceAvailableModels`| Treated as `true`. `forceLoginOrgUUID`| No organization is permitted to log in until the value is fixed. +`crossSessionInbound`| Treated as `refuse`, the most restrictive value, so inbound [cross-session messages](</docs/en/cross-session-messaging#control-inbound-messages>) are refused until the value is fixed. The developer sees [a warning](</docs/en/errors#crosssessioninbound-must-be-one-of-accept-hold-refuse>). `deniedMcpServers`| An individual invalid entry is stripped and the valid subset is enforced. A wholly invalid value is dropped with a warning, since denying every server would block servers the policy never named. `sandbox.credentials`| A recoverable invalid entry is degraded to `mode: "deny"` with a warning; an unrecoverable one is stripped; valid entries stay enforced. See [invalid credential entries](</docs/en/settings-reference#invalid-credential-entries-in-managed-settings>) @@ -253,11 +306,11 @@ Keys only a managed source can set -Claude Code reads the following keys only from a managed source; placing them in user or project settings files has no effect. Most of them are locks: the value a lock governs, such as permission rules or `sandbox.network.allowedDomains`, is an ordinary key that any level can set, and the lock tells Claude Code to honor only the managed value. The table covers the permission, plugin, and delivery controls. For any key not listed here, the Scope column of the [settings reference](</docs/en/settings-reference#all-settings>) index says whether it’s managed-only; the remaining managed-only keys there include the gateway login URL, version, browser, mobile-simulator, SSH host, Desktop local-session, sandbox binary path, and CLAUDE.md controls. +Claude Code reads the following keys only from a managed source; placing them in user or project settings files has no effect. Most of them are locks: the value a lock governs, such as permission rules or `sandbox.network.allowedDomains`, is an ordinary key that any level can set, and the lock tells Claude Code to honor only the managed value. The table covers the permission, plugin, and delivery controls. For any key not listed here, the Scope column of the [settings reference](</docs/en/settings-reference#all-settings>) index says whether it’s managed-only; the remaining managed-only keys there include the gateway login URL, version, browser, mobile-simulator, SSH host, Desktop local-session, sandbox binary path, model pricing, and CLAUDE.md controls. Setting| Description ---|--- -[`allowAllClaudeAiMcps`](</docs/en/settings-reference#allowallclaudeaimcps>)| Load the claude.ai connectors alongside a deployed `managed-mcp.json` instead of suppressing them +[`allowAllClaudeAiMcps`](</docs/en/settings-reference#allowallclaudeaimcps>)| Load the claude.ai connectors Claude Code fetches itself alongside a deployed `managed-mcp.json` instead of suppressing them [`allowedChannelPlugins`](</docs/en/settings-reference#allowedchannelplugins>)| Allowlist of channel plugins that may push messages. Replaces the default Anthropic allowlist when set. Requires `channelsEnabled: true`. See [Restrict which channel plugins can run](</docs/en/channels#restrict-which-channel-plugins-can-run>) [`allowManagedHooksOnly`](</docs/en/settings-reference#allowmanagedhooksonly>)| When `true`, restricts which hooks run; see [what runs under `allowManagedHooksOnly`](</docs/en/settings-reference#what-runs-under-allowmanagedhooksonly>) for the full effect list [`allowManagedMcpServersOnly`](</docs/en/settings-reference#allowmanagedmcpserversonly>)| When `true`, only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. See [Managed MCP configuration](</docs/en/managed-mcp>) @@ -267,6 +320,7 @@ [`disableCommandPluginSources`](</docs/en/settings-reference#disablecommandpluginsources>)| When `true`, blocks [`command` plugin sources](</docs/en/plugin-marketplaces#command-sources>) entirely, so the marketplace-declared command never runs. Also blocks marketplace [`headersHelper` commands](</docs/en/plugin-marketplaces#authenticate-archive-downloads>), except for a marketplace that managed settings themselves declare. When unset, follows `allowManagedHooksOnly`. Requires Claude Code v2.1.229 or later, and the `headersHelper` block requires v2.1.238 or later [`disableSideloadFlags`](</docs/en/settings-reference#disablesideloadflags>)| Reject the `--plugin-dir`, `--plugin-url`, `--agents`, and `--mcp-config` flags at startup. In cloud sessions, Claude Code drops the MCP servers the server delivered through `--mcp-config`, other than in-process `type: "sdk"` entries, and starts the session. Requires Claude Code v2.1.193 or later [`forceRemoteSettingsRefresh`](</docs/en/settings-reference#forceremotesettingsrefresh>)| When `true`, blocks CLI startup until remote managed settings are freshly fetched and exits if the fetch fails. See [fail-closed enforcement](</docs/en/server-managed-settings#enforce-fail-closed-startup>) +[`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>)| Whether Claude Code applies only the highest-priority managed source or composes every one of them [`parentSettingsBehavior`](</docs/en/settings-reference#parentsettingsbehavior>)| Whether host-supplied parent settings merge under the managed policy [`pluginSuggestionMarketplaces`](</docs/en/settings-reference#pluginsuggestionmarketplaces>)| Marketplaces whose plugins Claude Code may suggest to users [`pluginTrustMessage`](</docs/en/settings-reference#plugintrustmessage>)| Custom message appended to the plugin trust warning shown before installation @@ -275,7 +329,7 @@ [`sandbox.network.allowManagedDomainsOnly`](</docs/en/settings-reference#sandbox-network-allowmanageddomainsonly>)| Honor only managed `allowedDomains` and `WebFetch(domain:...)` allow rules; block other domains without prompting [`strictKnownMarketplaces`](</docs/en/settings-reference#strictknownmarketplaces>)| Controls which plugin marketplace sources users can add and install plugins from. See [managed marketplace restrictions](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>) [`strictPluginOnlyCustomization`](</docs/en/settings-reference#strictpluginonlycustomization>)| Block skills, agents, hooks, and MCP servers from user and project sources; `true` locks all four, an array names which -[`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>)| When set in the HKLM registry or a file under `C:\Program Files\ClaudeCode`, have WSL read the Windows policy chain, and read `/etc/claude-code` only when no managed settings file or drop-in under that directory delivers a policy key other than `wslInheritsWindowsSettings`; the entry gives the order +[`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>)| When set in the HKLM registry or a file under `C:\Program Files\ClaudeCode`, have WSL read the Windows policy chain, and read `/etc/claude-code` only when no managed settings file or drop-in under that directory delivers a policy key; the entry gives the order On Team and Enterprise plans, an Owner enables or disables [Remote Control](</docs/en/remote-control>) and [web sessions](</docs/en/claude-code-on-the-web>) organization-wide in [Claude Code admin settings](<https://claude.ai/admin-settings/claude-code>). Remote Control can additionally be disabled per device with the [`disableRemoteControl`](</docs/en/settings-reference#disableremotecontrol>) setting. Web sessions have no per-device managed settings key.
modified Connect to MCP servers View current →
--- a/mcp-quickstart.md +++ b/mcp-quickstart.md @@ -296,6 +296,7 @@ * You ran `claude mcp add` from a different project. Local-scoped servers are tied to the project where you added them: the repository root, or the exact directory if you weren’t in a git repository. Re-add the server from the project you’re in now, or add it with `--scope user` so it isn’t tied to a project. * You edited a configuration file at the wrong path. The correct files are `~/.claude.json` and `<project>/.mcp.json`. Claude Code doesn’t read paths such as `~/.claude/.mcp.json`, `~/.claude/config/mcp.json`, `~/.claude/mcp.json`, or `%APPDATA%\Claude\mcp.json`. For user-scoped servers, run `claude mcp add --scope user`, which writes to the `mcpServers` key in `~/.claude.json`; for project-scoped servers, edit `.mcp.json` at the project root. + * You wrote a malformed entry in `.mcp.json`. Claude Code skips that entry and still loads the others. Run `claude mcp list` from your shell and look for the parse warning, which names the offending field. Status shows Failed to connect or Connection error @@ -347,7 +348,7 @@ Changes to .mcp.json don't take effect -Claude Code reads `.mcp.json` at session start. Exit and restart the session after editing the file.If your servers still don’t appear, run `/mcp` and look for a parse warning. Claude Code skips malformed entries and shows the offending field there.If you previously rejected the server when prompted, reset project approvals: +Claude Code reads `.mcp.json` at session start. Exit and restart the session after editing the file.If your servers still don’t appear, run `claude mcp list` and look for a parse warning. Claude Code skips malformed entries and shows the offending field there.If you previously rejected the server when prompted, reset project approvals: claude mcp reset-project-choices
modified Migrate to Claude Agent SDK View current →
--- a/migration-guide.md +++ b/migration-guide.md @@ -46,23 +46,7 @@ // After import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk"; -**4\. Update package.json dependencies:** If you have the package listed in your `package.json`, update it: Before: - - { - "dependencies": { - "@anthropic-ai/claude-code": "^0.0.42" - } - } - -After: - - { - "dependencies": { - "@anthropic-ai/claude-agent-sdk": "^0.3.0" - } - } - -**5\. Reviewbreaking changes** Make any code changes needed to complete the migration. +**4\. Update package.json:** If `@anthropic-ai/claude-code` is still listed in your `package.json`, replace it with `@anthropic-ai/claude-agent-sdk` and update the version range as well, for example from `"^0.0.42"` to `"^0.3.0"`. **5\. Reviewbreaking changes** Make any code changes needed to complete the migration. ### @@ -175,59 +159,13 @@ asyncio.run(main()) -**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code’s CLI-focused instructions. - ### ​ Settings sources default -This default was briefly changed in v0.1.0 to load no filesystem settings and then reverted, so no migration action is needed. **Current behavior:** Omitting `settingSources` on `query()` loads user, project, and local filesystem settings, matching the CLI. This includes `~/.claude/settings.json`, `.claude/settings.json`, `.claude/settings.local.json`, CLAUDE.md files, and custom commands. To run isolated from filesystem settings, pass an empty array: - -TypeScript - -Python - - import { query } from "@anthropic-ai/claude-agent-sdk"; - - const isolatedResult = query({ - prompt: "Hello", - options: { - settingSources: [] // No filesystem settings loaded - } - }); - - // Or load only specific sources: - const projectOnlyResult = query({ - prompt: "Hello", - options: { - settingSources: ["project"] // Only project settings - } - }); - - from claude_agent_sdk import query, ClaudeAgentOptions - import asyncio - - async def main(): - async for message in query( - prompt="Hello", - options=ClaudeAgentOptions(setting_sources=[]), # No filesystem settings loaded - ): - print(message) - - # Or load only specific sources: - async for message in query( - prompt="Hello", - options=ClaudeAgentOptions( - setting_sources=["project"] # Only project settings - ), - ): - print(message) - - asyncio.run(main()) - -Isolation is especially important for CI/CD pipelines, deployed applications, test environments, and multi-tenant systems where local customizations should not leak in. +This default was briefly changed in v0.1.0 to load no filesystem settings and then reverted, so no migration action is needed. **Current behavior:** Omitting `settingSources` on `query()` loads user, project, and local filesystem settings, matching the CLI. This includes `~/.claude/settings.json`, `.claude/settings.json`, `.claude/settings.local.json`, CLAUDE.md files, and custom commands. To run isolated from filesystem settings, pass `settingSources: []`, or `setting_sources=[]` in Python. See [Control filesystem settings with settingSources](</docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources>) for what each source loads. Isolation is especially important for CI/CD pipelines, deployed applications, test environments, and multi-tenant systems where local customizations should not leak in. Python SDK 0.1.59 and earlier treated an empty list the same as omitting the option, so upgrade before relying on `setting_sources=[]`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read even when `settingSources` is `[]`.
modified Model configuration View current →
--- a/model-config.md +++ b/model-config.md @@ -200,10 +200,10 @@ Delivery mechanism| CLI and IDE| Desktop local sessions| Web, mobile, and cloud sessions| Agent SDK and non-interactive| Cowork ---|---|---|---|---|--- [Server-managed settings](</docs/en/server-managed-settings>) from the admin console| Enforced| Enforced| Enforced| Enforced| Not delivered -[MDM or managed settings files](</docs/en/managed-settings#delivery-mechanisms>)| Enforced| Enforced| Not delivered in Anthropic-hosted environments; in [self-hosted environments](</docs/en/self-hosted-environments>), enforced from the runner image when server-managed settings deliver no keys| Enforced| Enforced where deployed - - * Cloud sessions, on [Claude Code on the web](</docs/en/claude-code-on-the-web>) or in the Desktop app, run on Anthropic-managed VMs by default: settings deployed to your device do not reach them, so deliver the allowlist through server-managed settings. Sessions your organization routes to a [self-hosted environment](</docs/en/self-hosted-environments>) run on your own compute and fall back to the managed settings file in the runner image when your organization delivers no server-managed settings; when both exist, the server-managed payload takes precedence, apart from the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>). A mid-session model switch in a cloud session is rejected when the requested model is excluded by the allowlist. Server-side rejection at session creation applies to organization model restrictions, not the `availableModels` settings key. - * Cowork, the agentic-work tab in the Claude Desktop app, is not a Claude Code surface and does not receive server-managed settings by design. A managed settings file applies to Cowork sessions when it is present where the session runs; remote Cowork sessions run on Anthropic-managed VMs, where a device-deployed file is not present. +[MDM or managed settings files](</docs/en/managed-settings#delivery-mechanisms>)| Enforced| Enforced| Not delivered in Anthropic-hosted environments; in [self-hosted environments](</docs/en/self-hosted-environments>), enforced from the runner image per [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>)| Enforced| Enforced where deployed + + * Cloud sessions, on [Claude Code on the web](</docs/en/claude-code-on-the-web>) or in the Desktop app, run on Anthropic-managed VMs by default: settings deployed to your device do not reach them, so deliver the allowlist through server-managed settings. Sessions your organization routes to a [self-hosted environment](</docs/en/self-hosted-environments>) run on your own compute and also read the managed settings file in the runner image. [How Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) says when that file applies. A mid-session model switch in a cloud session is rejected when the requested model is excluded by the allowlist. Server-side rejection at session creation applies to organization model restrictions, not the `availableModels` settings key. + * Cowork, the agentic-work tab in the Claude Desktop app, runs its sessions on Claude Code but, by design, does not receive server-managed settings from the claude.ai admin console. A managed settings file applies to Cowork sessions when it is present where the session runs; remote Cowork sessions run on Anthropic-managed VMs, where a device-deployed file is not present. * Sessions on [third-party providers](</docs/en/server-managed-settings#platform-availability>) such as Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) do not receive server-managed settings, so deliver the allowlist through MDM or managed settings files there. * Server-managed delivery also requires the session to authenticate with an [eligible login or key](</docs/en/server-managed-settings#platform-availability>). Fleets that generate keys only through an [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) script should deliver the allowlist through MDM or managed settings files. * The Desktop Code tab also hosts [SSH sessions](</docs/en/desktop#ssh-sessions>), which read the managed settings file from the remote host they run on. See [Desktop managed settings](</docs/en/desktop#managed-settings>). @@ -230,7 +230,7 @@ "enforceAvailableModels": true } -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` remaps the Default option only when `availableModels` is non-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/managed-settings#precedence-within-the-managed-tier>): these keys don’t merge across managed sources, 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` remaps the Default option only when `availableModels` is non-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 together in the highest-ranked managed source you deliver. By default Claude Code reads only that source, so a pair placed in a managed settings file is ignored when the admin console delivers any settings; under the opt-in merge in [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>), Claude Code still ignores a `modelOverrides` map from a source ranked below the one that sets `availableModels`. ### @@ -264,7 +264,7 @@ Merge behavior -When the [highest-precedence managed settings source](</docs/en/server-managed-settings#settings-precedence>) defines `availableModels`, that list alone applies, apart from a [host platform that supplies its own](</docs/en/settings#exceptions-to-managed-settings-precedence>): entries in user, project, or local settings cannot extend it, and `availableModels` doesn’t merge across admin-deployed managed sources, so a list deployed in a managed settings file is ignored when server-managed settings deliver any keys. Otherwise, lists from user, project, and local settings are [concatenated and deduplicated](</docs/en/settings#settings-precedence>) like other array settings. As of Claude Code v2.1.175, the managed list replaces lower-precedence entries; earlier versions merge them. Within the effective list, an entry naming a specific model in a family, whether a version prefix or a full model ID, disables that family’s wildcard entry: `["sonnet", "claude-sonnet-4-5"]` allows only Sonnet 4.5 versions, not every Sonnet model. +When the managed settings Claude Code applies define `availableModels`, that list alone applies, apart from a [host platform that supplies its own](</docs/en/settings#exceptions-to-managed-settings-precedence>): entries in user, project, or local settings cannot extend it, and Claude Code never merges `availableModels` across managed sources either; [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) says which source’s list applies. Otherwise, lists from user, project, and local settings are [concatenated and deduplicated](</docs/en/settings#settings-precedence>) like other array settings. Before Claude Code v2.1.175, entries from lower-precedence scopes merged into the managed list instead of being replaced by it. Within the effective list, an entry naming a specific model in a family, whether a version prefix or a full model ID, disables that family’s wildcard entry: `["sonnet", "claude-sonnet-4-5"]` allows only Sonnet 4.5 versions, not every Sonnet model. ### @@ -371,6 +371,8 @@ * **Outside the allowlist** : Claude Code drops any entry not permitted by `availableModels` when it reads the chain. * **Smaller context window during compaction** : the chain also covers [compaction](</docs/en/context-window#what-survives-compaction>), but Claude Code won’t fall back to a model with a smaller context window than the primary’s, since summarizing there would cut off part of the conversation first. If every fallback is smaller, compaction shows the original error and you can retry. + +Claude Code also applies the chain to [subagents](</docs/en/sub-agents>). When a subagent’s request fails over, Claude Code tries your configured fallback models in order, and the subagent continues on the model that accepts the request. Your session’s model is unchanged. Before v2.1.247, a failure the chain covers ended the subagent instead. ### @@ -739,7 +741,7 @@ } } -Keys must be Anthropic model IDs as listed in the [Models overview](<https://platform.claude.com/docs/en/about-claude/models/overview>). For dated model IDs, include the date suffix exactly as it appears there. Unknown keys are ignored. To stop the `[claude-code:unrecognized_model]` [diagnostic line](</docs/en/errors#unrecognized-model-id-on-a-request>) for an ID such as a gateway alias, add an entry with that ID as its value. Overrides replace the built-in model IDs that back each entry in the `/model` picker. On Amazon Bedrock, `modelOverrides` entries take precedence over any inference profiles that Claude Code discovers automatically at startup. Claude Code passes values that are already provider-native, such as Amazon Bedrock inference profile ARNs or Microsoft Foundry deployment names, to the provider as-is. Overrides also apply when you pass an Anthropic model ID directly through `--model`, the `ANTHROPIC_MODEL` environment variable, or an `ANTHROPIC_DEFAULT_*_MODEL` environment variable. On Amazon Bedrock, Google Cloud’s Agent Platform, and [Mantle](</docs/en/amazon-bedrock#use-the-mantle-endpoint>), an Anthropic model ID with no `modelOverrides` entry resolves to the same provider-specific ID as the `/model` picker row for that version, when the provider supports that version. Mantle supports a subset of versions. For an Anthropic model ID outside that subset, Claude Code sends the raw ID to Mantle without mapping it, unless a `modelOverrides` entry covers it. Before v2.1.200, `--model` and the environment-variable values reached the provider as-is without going through the override map. `modelOverrides` works alongside `availableModels`. The allowlist is evaluated against the Anthropic model ID, not the override value, so an entry like `"opus"` in `availableModels` continues to match even when Opus versions are mapped to ARNs. When `enforceAvailableModels` is set in managed settings, the enforced Default resolves through `modelOverrides` from the [highest-precedence managed source](</docs/en/server-managed-settings#settings-precedence>) only. An admin’s mapping, such as a version pinned to an inference profile ARN, is honored in the enforced Default. Overrides from user or project settings do not affect it. When `availableModels` is set in [managed settings](</docs/en/managed-settings>), only `modelOverrides` from that managed source apply to an Anthropic model ID passed directly through `--model` or the environment variables above. Claude Code ignores overrides in user or project settings for those IDs, and never resolves an ID the managed list excludes through `modelOverrides` from any settings source. This managed-source restriction requires Claude Code v2.1.200 or later. See Restrict model selection for how blocked IDs are handled. +Keys must be Anthropic model IDs as listed in the [Models overview](<https://platform.claude.com/docs/en/about-claude/models/overview>). For dated model IDs, include the date suffix exactly as it appears there. Unknown keys are ignored. To stop the `[claude-code:unrecognized_model]` [diagnostic line](</docs/en/errors#unrecognized-model-id-on-a-request>) for an ID such as a gateway alias, add an entry with that ID as its value. Overrides replace the built-in model IDs that back each entry in the `/model` picker. On Amazon Bedrock, `modelOverrides` entries take precedence over any inference profiles that Claude Code discovers automatically at startup. Claude Code passes values that are already provider-native, such as Amazon Bedrock inference profile ARNs or Microsoft Foundry deployment names, to the provider as-is. Overrides also apply when you pass an Anthropic model ID directly through `--model`, the `ANTHROPIC_MODEL` environment variable, or an `ANTHROPIC_DEFAULT_*_MODEL` environment variable. On Amazon Bedrock, Google Cloud’s Agent Platform, and [Mantle](</docs/en/amazon-bedrock#use-the-mantle-endpoint>), an Anthropic model ID with no `modelOverrides` entry resolves to the same provider-specific ID as the `/model` picker row for that version, when the provider supports that version. Mantle supports a subset of versions. For an Anthropic model ID outside that subset, Claude Code sends the raw ID to Mantle without mapping it, unless a `modelOverrides` entry covers it. Before v2.1.200, `--model` and the environment-variable values reached the provider as-is without going through the override map. `modelOverrides` works alongside `availableModels`. The allowlist is evaluated against the Anthropic model ID, not the override value, so an entry like `"opus"` in `availableModels` continues to match even when Opus versions are mapped to ARNs. When `enforceAvailableModels` is set in managed settings, the enforced Default resolves through `modelOverrides` from [managed settings](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) only. An admin’s mapping, such as a version pinned to an inference profile ARN, is honored in the enforced Default. Overrides from user or project settings do not affect it. When `availableModels` is set in [managed settings](</docs/en/managed-settings>), only `modelOverrides` from managed settings apply to an Anthropic model ID passed directly through `--model` or the environment variables above. Claude Code ignores overrides in user or project settings for those IDs, and never resolves an ID the managed list excludes through `modelOverrides` from any settings source. This managed-source restriction requires Claude Code v2.1.200 or later. See Restrict model selection for how blocked IDs are handled. ###
modified Monitoring View current →
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1143,7 +1143,7 @@ Retention sweep event -Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. When `managed-settings.json` itself can’t be read or parsed, Claude Code still pauses the sweep unless the [managed source it selects](</docs/en/server-managed-settings#settings-precedence>) supplies `cleanupPeriodDays` from elsewhere, such as server-managed settings or a `managed-settings.d/` drop-in beside the broken file. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : +Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. When `managed-settings.json` itself can’t be read or parsed, Claude Code still pauses the sweep unless the [managed tier](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) supplies `cleanupPeriodDays` from elsewhere, such as server-managed settings or a `managed-settings.d/` drop-in beside the broken file. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : * All standard attributes * `event.name`: `"retention_sweep"`
modified Enterprise network configuration View current →
--- a/network-config.md +++ b/network-config.md @@ -194,13 +194,13 @@ `claude.ai`| claude.ai account authentication `claude.com`| claude.ai account sign-in opens a `claude.com` page in the browser, which redirects to `claude.ai`; pre-approved WebFetch documentation lookups also reach this host from the CLI `platform.claude.com`| Anthropic Console account authentication. OAuth token exchange, refresh, and revocation also go to this host for claude.ai accounts, so both Console and claude.ai sign-ins require it -`mcp-proxy.anthropic.com`| [MCP connectors from claude.ai](</docs/en/mcp#use-mcp-servers-from-claude-ai>), including connectors an organization administrator configures. Connector traffic routes through this proxy; connectors are enabled by default for claude.ai-authenticated users. To disable, set [`ENABLE_CLAUDEAI_MCP_SERVERS=false`](</docs/en/env-vars>) or the [`disableClaudeAiConnectors`](</docs/en/settings-reference#disableclaudeaiconnectors>) setting +`mcp-proxy.anthropic.com`| [MCP connectors from claude.ai](</docs/en/mcp#use-mcp-servers-from-claude-ai>), including connectors an organization administrator configures. Connector traffic routes through this proxy; connectors are enabled by default for claude.ai-authenticated users. To stop Claude Code from fetching them, set [`ENABLE_CLAUDEAI_MCP_SERVERS=false`](</docs/en/env-vars>) or the [`disableClaudeAiConnectors`](</docs/en/settings-reference#disableclaudeaiconnectors>) setting `downloads.claude.ai`| Plugin executable downloads; native installer, native auto-updater, and update version checks `storage.googleapis.com`| Plugin install counts and metadata shown in `/plugin` `storage.googleapis.com`| Native installer and native auto-updater on versions prior to 2.1.116 `registry.npmjs.org`| Plugin installs (fetching npm-source plugin packages and installing plugins’ Node.js package dependencies), `npx`-launched MCP servers, and the package registry for npm and bun installs of Claude Code itself `bridge.claudeusercontent.com`| [Claude in Chrome](</docs/en/chrome>) extension WebSocket bridge -`*.frame.claudeusercontent.com`| [Artifact](</docs/en/artifacts>) content reads. The CLI fetches an artifact’s files from this host when Claude opens one, and only when the Artifact tool is [available](</docs/en/artifacts#availability>) for your account. To disable the tool and drop this requirement, set [`CLAUDE_CODE_DISABLE_ARTIFACT=1`](</docs/en/env-vars>) or the [`disableArtifact`](</docs/en/settings-reference#disableartifact>) setting +`*.frame.claudeusercontent.com`| [Artifact](</docs/en/artifacts>) content reads. The CLI fetches an artifact’s files from this host when Claude opens one, and only when the Artifact tool is [available](</docs/en/artifacts#availability>) for your account. To turn the tool off and drop this requirement, set [`"enableArtifact": false`](</docs/en/settings-reference#enableartifact>) or [`CLAUDE_CODE_DISABLE_ARTIFACT=1`](</docs/en/env-vars>); Claude Code also honors the deprecated [`disableArtifact`](</docs/en/settings-reference#disableartifact>) setting. See [Disable artifacts](</docs/en/artifacts#disable-artifacts>) for how these settings interact `raw.githubusercontent.com`| Changelog feed for [`/release-notes`](</docs/en/commands>) and the release notes shown after updating `http-intake.logs.us5.datadoghq.com`| Operational telemetry events, sent only when the CLI uses the Anthropic API directly, never for Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. Optional: disable with [`DISABLE_TELEMETRY`](</docs/en/data-usage#telemetry-services>) or `DO_NOT_TRACK` `browser-intake-us5-datadoghq.com`| Operational error reports, sent when the CLI uses the Anthropic API directly and a server-side rollout gate enables them. Optional: disable with `DISABLE_ERROR_REPORTING` or `DISABLE_TELEMETRY`; see [Telemetry services](</docs/en/data-usage#telemetry-services>) @@ -231,7 +231,7 @@ Desktop and claude.ai -The preceding table covers the standalone CLI. The Claude Desktop app and claude.ai in a browser load their application code and user content from additional Anthropic CDN hosts, including `assets-proxy.anthropic.com` and the other `*.claudeusercontent.com` origins that serve [artifacts](</docs/en/artifacts>) in those apps. Allowing `claude.ai` while blocking those hosts produces a blank page rather than an error. See [network access requirements](</docs/en/desktop#network-access-requirements>) on the Desktop page. An [artifact](</docs/en/artifacts>) that loads a typeface from [Google Fonts](</docs/en/artifacts#improve-the-visual-design>) also requests `fonts.googleapis.com` and `fonts.gstatic.com`. Both hosts are optional. If you block them, artifacts render in fallback typefaces. Block with a fast rejection rather than a silent drop so the font request fails immediately instead of delaying the page’s first render. +The preceding table covers the standalone CLI. The Claude Desktop app and claude.ai in a browser load their application code and user content from additional Anthropic CDN hosts, including `assets-proxy.anthropic.com` and the other `*.claudeusercontent.com` origins that serve [artifacts](</docs/en/artifacts>) in those apps. Allowing `claude.ai` while blocking those hosts produces a blank page rather than an error. See [network access requirements](</docs/en/desktop#network-access-requirements>) on the Desktop page. An [artifact](</docs/en/artifacts>) that loads a typeface from [Google Fonts](</docs/en/artifacts#improve-the-visual-design>) also requests `fonts.googleapis.com` and `fonts.gstatic.com`. Both hosts are optional. If you block them, artifacts render in fallback typefaces. Block with a fast rejection rather than a silent drop so the font request fails immediately instead of delaying the page’s first render. Artifacts can also load JavaScript libraries, such as React or a charting package, from `cdnjs.cloudflare.com`, `cdn.jsdelivr.net`, `cdn.tailwindcss.com`, and `code.jquery.com`, and from no other external host. If you block those hosts, the parts of an artifact that depend on a library don’t work, and unlike a blocked font, a blocked library has no fallback. Block with a fast rejection here too, so a blocked library request fails at once rather than hanging until it times out. ##
modified Output styles View current →
--- a/output-styles.md +++ b/output-styles.md @@ -103,8 +103,8 @@ Output styles directly modify Claude Code’s system prompt. - * Claude Code adds each output style’s custom instructions to the end of the system prompt. - * All output styles trigger reminders for Claude to adhere to the output style instructions during the conversation. + * Claude Code adds the output style’s custom instructions to the system prompt. + * When you select a style other than Default, Claude Code also reminds Claude of the style during the conversation. * Custom output styles leave out Claude Code’s built-in software engineering instructions, such as how to scope changes, write comments, and verify work, unless `keep-coding-instructions` is set to `true`. Output styles apply to the main conversation only: a [subagent runs its own system prompt](</docs/en/sub-agents#what-loads-at-startup>), so styles don’t change how subagents respond. A [fork](</docs/en/sub-agents#fork-the-current-conversation>) is the exception, because it inherits the parent’s full system prompt. Token usage depends on the style. Adding instructions to the system prompt increases input tokens, though prompt caching reduces this cost after the first request in a session. The built-in Explanatory and Learning styles produce longer responses than Default by design, which increases output tokens, and the Concise style does the opposite by instructing Claude to keep responses short by default. For custom styles, output token usage depends on what your instructions tell Claude to produce.
modified Choose a permission mode View current →
--- a/permission-modes.md +++ b/permission-modes.md @@ -28,7 +28,7 @@ Claude Code doesn’t auto-approve the following in any mode, including `bypassPermissions`. Each bullet links to the section that says what happens instead in each mode: * Tools matched by an explicit [ask rule](</docs/en/permissions#manage-permissions>) - * Connector tools your organization [set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) + * Connector tools your organization [set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), in sessions where that setting reaches Claude Code * Tools that require user interaction: the built-in `AskUserQuestion` tool and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) * `rm` and `rmdir` removals targeting a critical path, which no allow rule or `PreToolUse` hook `"allow"` approves * The cross-session messaging safeguards @@ -39,14 +39,14 @@ Common setups -Permission modes decide whether Claude asks before an action, and the [Bash sandbox](</docs/en/sandboxing>) and outer [isolation boundaries](</docs/en/sandbox-environments>) decide what an action can reach once it runs. Each row below pairs a goal with the flags or settings that get you there and the isolation it needs, as a starting point. Available modes lists what runs without a prompt in each mode, and the per-mode section each row links carries the full behavior. +Permission modes decide whether Claude asks before an action, and the [Bash sandbox](</docs/en/sandboxing>) and outer [isolation boundaries](</docs/en/sandbox-environments>) decide what an action can reach once it runs. Each row below pairs a goal with the flags or settings that get you there and the isolation it needs, as a starting point. Available modes lists what runs without a prompt in each mode. You want to| Start with| Isolation needed| Notes ---|---|---|--- Review every action yourself| Manual mode: `claude --permission-mode default`| None| Sensitive work, unfamiliar code Iterate locally with fewer prompts, without a classifier| Manual mode plus the Bash sandbox in [auto-allow mode](</docs/en/sandboxing#sandbox-modes>): `claude --permission-mode default`, then run `/sandbox` and select auto-allow| The built-in Bash sandbox, on macOS, Linux, and WSL2| Deny rules still apply, and ask rules that name a command, such as `Bash(git push *)`, still prompt. To turn the sandbox on from a settings file instead, set [`sandbox.enabled`](</docs/en/settings-reference#sandbox-enabled>) to `true` Explore before changing anything| `claude --permission-mode plan`| None| Claude Code blocks edits until you approve a plan -Work hands-off with a classifier reviewing each action| `claude --permission-mode auto`, the built-in starting permission mode on Pro, Max, and Team| None; a sandbox or container adds defense in depth| Requires a supported model, and your organization can turn auto mode off +Work hands-off in auto mode| `claude --permission-mode auto`, the built-in starting permission mode on Pro, Max, and Team| None; a sandbox or container adds defense in depth| Requires a supported model, and your organization can turn auto mode off Run in CI with an exact allowlist| `claude -p "run the test suite" --permission-mode dontAsk --allowedTools "Bash(npm test)" "Read"`| None beyond what your CI runner provides| [Claude Code on the web](</docs/en/claude-code-on-the-web>) ignores `dontAsk` from settings files Run fully unattended inside a container| `claude -p "<prompt>" --dangerously-skip-permissions`| Required: a container, VM, or the [sandbox runtime](</docs/en/sandbox-environments#sandbox-runtime>); on Linux and macOS, run it as a non-root user| Claude Code on the web ignores this mode from settings files. In this `-p` run, the few calls that would still prompt are denied instead @@ -64,7 +64,7 @@ 2. `permissions.defaultMode` in a [settings file](</docs/en/settings#where-settings-live>). An `"auto"` value in `.claude/settings.json` or `.claude/settings.local.json` doesn’t take effect, and Claude Code then uses the built-in default rather than a `defaultMode` from `~/.claude/settings.json`. The other values apply from any settings file 3. The built-in default -Conversations the VS Code extension starts follow the extension’s own list in Switch permission modes. A session you resume keeps the permission mode it was in unless you pass `--permission-mode` or `--dangerously-skip-permissions`; [what a resumed session restores](</docs/en/sessions#what-a-resumed-session-restores>) lists the exceptions. The built-in `auto` default requires Claude Code v2.1.228 or later on macOS, Linux, and WSL, and v2.1.233 or later on native Windows. On earlier versions, the built-in default is Manual. The built-in default depends on how you run Claude Code, on your plan, and on whether Claude Code could fetch its feature flags. The first row that matches your session applies. The table covers sessions you start in a terminal or through the VS Code extension; for the desktop app and claude.ai, see the Desktop and Web tabs in Switch permission modes. +Conversations the VS Code extension starts follow the extension’s own list in Switch permission modes. For the permission mode Claude Code starts a resumed session in, see [permission mode on resume](</docs/en/sessions#permission-mode-on-resume>). The built-in `auto` default requires Claude Code v2.1.228 or later on macOS, Linux, and WSL, and v2.1.233 or later on native Windows. On earlier versions, the built-in default is Manual. The built-in default depends on how you run Claude Code, on your plan, and on whether Claude Code could fetch its feature flags. The first row that matches your session applies. The table covers sessions you start in a terminal or through the VS Code extension; for the desktop app and claude.ai, see the Desktop and Web tabs in Switch permission modes. How you run Claude Code| Built-in starting permission mode ---|--- @@ -132,7 +132,7 @@ * `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in [settings](</docs/en/settings-reference#permission-settings>); the `--allow-` variant adds the permission mode to the cycle without activating it * `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk` -Enabled optional modes slot in after `plan`, with `bypassPermissions` first and `auto` last. If you have both enabled, you will cycle through `bypassPermissions` on the way to `auto`.**At startup** : pass the permission mode as a flag. +Enabled optional modes slot in after `plan`, with `bypassPermissions` first and `auto` last. If you have both enabled, you will cycle through `bypassPermissions` on the way to `auto`.**From a Bash permission prompt** : in the Manual and `acceptEdits` permission modes, when auto mode is available, Claude Code adds **Yes, and switch to auto mode** to a Bash command’s permission prompt. Select it to approve the command and switch the session to auto mode. [PowerShell tool](</docs/en/tools-reference#powershell-tool>) prompts don’t offer the option. Requires Claude Code v2.1.247 or later.Claude Code doesn’t add the option to prompts forced by one of your [`ask` rules](</docs/en/permissions#manage-permissions>) or by a [hook](</docs/en/hooks#pretooluse-decision-control>), because auto mode still shows you those prompts, so switching wouldn’t remove them.**At startup** : pass the permission mode as a flag. claude --permission-mode plan @@ -365,9 +365,9 @@ Each action goes through a fixed decision order. The first matching step wins: - 1. Actions matching your [allow, ask, or deny rules](</docs/en/permissions#manage-permissions>) resolve immediately. Writes to protected paths route to the classifier even when an allow rule matches, and so do `rm` and `rmdir` removals targeting a critical path in Claude Code v2.1.218 and later. Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) prompt you directly even when an allow rule matches. Ask rules that match on a command’s content, such as `Bash(git push *)`, fall back to a permission prompt + 1. Actions matching your [allow, ask, or deny rules](</docs/en/permissions#manage-permissions>) resolve immediately. Writes to protected paths route to the classifier even when an allow rule matches, and so do `rm` and `rmdir` removals targeting a critical path in Claude Code v2.1.218 and later. MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) prompt you directly even when an allow rule matches, and so do connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. Ask rules that match on a command’s content, such as `Bash(git push *)`, fall back to a permission prompt 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, except the org-set-to-`ask` connector tools and `requiresUserInteraction` MCP tools from step 1, which always prompt you directly, so neither an org-required approval nor a consent step is auto-approved + 3. Everything else goes to the classifier. The connector tools and `requiresUserInteraction` MCP tools that prompt you directly in step 1 never reach the classifier, so neither an org-required approval nor a consent step is auto-approved 4. If the classifier blocks, Claude receives the reason and tries an alternative. In most sessions the reason is the fixed text `Blocked by classifier` rather than a written explanation, in Claude Code v2.1.208 and later; see [Review denials](</docs/en/auto-mode-config#review-denials>) On entering auto mode, broad allow rules that grant arbitrary code execution are dropped: @@ -400,7 +400,7 @@ Allow only pre-approved tools with dontAsk mode -If you set `dontAsk` mode, Claude Code auto-denies every tool call that would otherwise prompt you. Claude runs only actions matching your `permissions.allow` rules, [read-only Bash commands](</docs/en/permissions#read-only-commands>), and calls approved by a [PreToolUse hook](</docs/en/permissions#extend-permissions-with-hooks>). Use this mode for CI pipelines or restricted environments where you pre-define exactly what Claude may do; the session never waits for input. The status bar shows `⏵⏵ don't ask on` while this mode is active. Claude Code denies calls matching your explicit [`ask` rules](</docs/en/permissions#manage-permissions>) rather than prompting. It also denies the built-in `AskUserQuestion` tool and connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), even if your allow rules match them. It denies MCP tools marked [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) the same way, because their approval card needs an answer this mode never collects; this requires Claude Code v2.1.199 or later. `rm` and `rmdir` removals targeting a critical path, such as `rm -rf /` and `rm -rf ~`, are denied even when an allow rule matches them or a `PreToolUse` hook allows them. 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: +If you set `dontAsk` mode, Claude Code auto-denies every tool call that would otherwise prompt you. Claude runs only actions matching your `permissions.allow` rules, [read-only Bash commands](</docs/en/permissions#read-only-commands>), and calls approved by a [PreToolUse hook](</docs/en/permissions#extend-permissions-with-hooks>). Use this mode for CI pipelines or restricted environments where you pre-define exactly what Claude may do; the session never waits for input. The status bar shows `⏵⏵ don't ask on` while this mode is active. Claude Code denies calls matching your explicit [`ask` rules](</docs/en/permissions#manage-permissions>) rather than prompting. It also denies the built-in `AskUserQuestion` tool even if your allow rules match it, and does the same to connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. It denies MCP tools marked [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) the same way, because their approval card needs an answer this mode never collects; this requires Claude Code v2.1.199 or later. `rm` and `rmdir` removals targeting a critical path, such as `rm -rf /` and `rm -rf ~`, are denied even when an allow rule matches them or a `PreToolUse` hook allows them. 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 @@ -423,7 +423,7 @@ claude --permission-mode bypassPermissions -The `--dangerously-skip-permissions` flag is equivalent. The first time you start an interactive session with this mode enabled, Claude Code shows a warning dialog asking you to accept responsibility for actions taken without permission checks. Claude Code saves your acceptance to user settings, so the dialog appears only once. If you decline, Claude Code exits. In [non-interactive mode](</docs/en/headless>) no dialog is shown, and a [background session](</docs/en/agent-view>) started with `--bg` is refused until you’ve accepted the dialog in an interactive session. On Linux and macOS, Claude Code refuses to start in this mode when running as root or under `sudo`: +The `--dangerously-skip-permissions` flag is equivalent. Claude Code refuses `bypassPermissions` in a session you start with [`--restricted`](</docs/en/cli-reference#cli-flags>). `--restricted` requires Claude Code v2.1.248 or later. The first time you start an interactive session with this mode enabled, Claude Code shows a warning dialog asking you to accept responsibility for actions taken without permission checks. Claude Code saves your acceptance to user settings, so the dialog appears only once. If you decline, Claude Code exits. In [non-interactive mode](</docs/en/headless>) no dialog is shown, and a [background session](</docs/en/agent-view>) started with `--bg` is refused until you’ve accepted the dialog in an interactive session. On Linux and macOS, Claude Code refuses to start in this mode when running as root or under `sudo`: --dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons
modified Constrain plugin dependency versions View current →
--- a/plugin-dependencies.md +++ b/plugin-dependencies.md @@ -97,6 +97,21 @@ ​ +Test a plugin and its dependency locally + +If you’re developing a plugin and the plugin it depends on at the same time, load both with `--plugin-dir`: + + claude --plugin-dir ./my-dependency --plugin-dir ./my-plugin + +The local copy of the dependency satisfies your plugin’s dependency entry, even when the entry names a marketplace, so you don’t need to install the dependency from its marketplace. Claude Code doesn’t check a version constraint against a local copy, so the local `plugin.json` doesn’t need a `version`. Before v2.1.242, a dependency entry that named a marketplace never matched the local copy, and Claude Code disabled your plugin at load. If you haven’t installed the dependency from its marketplace, your plugin stops loading when the local copy goes away: + + * **You disabled the local copy** : Claude Code disables your plugin at the next plugin load. For a dependency entry that names a marketplace, Claude Code reports `Dependency "<name>@inline" is disabled — enable it or remove the dependency`; for a bare-name entry, it reports the dependency by its bare name. `<name>@inline` is how Claude Code identifies every `--plugin-dir` and `--plugin-url` plugin. + * **You started a session without the dependency’s`--plugin-dir` flag**: Claude Code reports the dependency as not installed. Pass the flag again, or install the dependency from its marketplace. + +## + +​ + Tag plugin releases for version resolution Claude Code resolves version constraints against git tags on the repository that hosts the dependency: the plugin’s own repository for `github`, `url`, and `git-subdir` [plugin sources](</docs/en/plugin-marketplaces#plugin-sources>), or the marketplace repository for a plugin the marketplace references by a relative path. For Claude Code to find a dependency’s available versions, the upstream plugin’s releases must be tagged using a specific naming convention. Tag each release as `{plugin-name}--v{version}`, where `{version}` matches the `version` field in that commit’s `plugin.json`. From the plugin directory, run: @@ -141,7 +156,7 @@ Enable or disable a plugin with dependencies -Enabling a plugin also enables the plugins it depends on, and disabling a plugin is blocked if another enabled plugin still needs it. When you enable a plugin, Claude Code also enables its dependencies at the same scope. If a dependency has its own dependencies, Claude Code enables those too. The success message lists what else was enabled along with the plugin you named. If a dependency can’t be enabled, the command refuses and tells you what’s blocking and how to fix it: +This section covers plugins installed from a marketplace. For a copy you loaded with `--plugin-dir`, see Test a plugin and its dependency locally. Enabling a plugin also enables the plugins it depends on, and disabling a plugin is blocked if another enabled plugin still needs it. When you enable a plugin, Claude Code also enables its dependencies at the same scope. If a dependency has its own dependencies, Claude Code enables those too. The success message lists what else was enabled along with the plugin you named. If a dependency can’t be enabled, the command refuses and tells you what’s blocking and how to fix it: Condition| Result ---|---
modified Create and distribute a plugin marketplace View current →
--- a/plugin-marketplaces.md +++ b/plugin-marketplaces.md @@ -162,7 +162,7 @@ Field| Type| Description| Example ---|---|---|--- -`name`| string| Marketplace identifier (kebab-case, no spaces). This is public-facing: users see it when installing plugins (for example, `/plugin install my-tool@your-marketplace`). Each user can register only one marketplace per name: adding a second marketplace with the same name replaces the first. To publish multiple plugins under one marketplace name, list them all in a single `marketplace.json`.| `"acme-tools"` +`name`| string| Marketplace identifier in kebab-case, with no spaces, control characters, or bidirectional-formatting characters. This is public-facing: users see it when installing plugins (for example, `/plugin install my-tool@your-marketplace`). Each user can register only one marketplace per name: when they add a second marketplace with the same name, Claude Code replaces the first. To publish multiple plugins under one marketplace name, list them all in a single `marketplace.json`.| `"acme-tools"` `owner`| object| Marketplace maintainer information (see fields below)| `plugins`| array| List of available plugins| See below @@ -213,7 +213,7 @@ Field| Type| Description ---|---|--- -`name`| string| Plugin identifier (kebab-case, no spaces). This is public-facing: users see it when installing (for example, `/plugin install my-plugin@marketplace`). +`name`| string| Plugin identifier in kebab-case, with no spaces, control characters, or bidirectional-formatting characters. This is public-facing: users see it when installing (for example, `/plugin install my-plugin@marketplace`). `source`| string|object| Where to fetch the plugin from (see Plugin sources below) ### @@ -238,8 +238,8 @@ `category`| string| Plugin category for organization `tags`| array| Tags for searchability `strict`| boolean| Controls whether `plugin.json` is the authority for component definitions (default: true). See Strict mode below. -`relevance`| object| Signals that tell Claude Code when to suggest this plugin to users. Takes effect only for marketplaces an administrator allowlists in managed settings. See [Recommend plugins for your org](</docs/en/plugin-relevance>). Requires Claude Code v2.1.152 or later. -`defaultEnabled`| boolean| Whether the plugin is enabled after install (default: true). Set to `false` to install the plugin disabled until the user opts in. Takes precedence over the same field in the plugin’s `plugin.json`. See [Default enablement](</docs/en/plugins-reference#default-enablement>). Requires Claude Code v2.1.154 or later. +`relevance`| object| Signals that tell Claude Code when to suggest this plugin to users. Takes effect only for marketplaces an administrator allowlists in managed settings. See [Recommend plugins for your org](</docs/en/plugin-relevance>). +`defaultEnabled`| boolean| Whether the plugin is enabled after install (default: true). Set to `false` to install the plugin disabled until the user opts in. Takes precedence over the same field in the plugin’s `plugin.json`. See [Default enablement](</docs/en/plugins-reference#default-enablement>). **Component configuration fields:** @@ -1022,7 +1022,7 @@ * For `hostPattern` sources: the marketplace host is matched against the regex pattern * For `pathPattern` sources: the marketplace’s filesystem path is matched against the regex pattern -The allowlist’s exact matching doesn’t normalize URLs: a trailing slash, `.git` suffix, or `ssh://` versus `https://` form are treated as different values. If your organization’s marketplace can be cloned by more than one URL form, prefer a `hostPattern` entry over a literal URL so all forms match. Because `strictKnownMarketplaces` is set in [managed settings](</docs/en/managed-settings>), individual users and project configurations can’t override these restrictions. For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](</docs/en/settings-reference#strictknownmarketplaces>). +The allowlist’s exact matching treats URLs that differ only by a trailing slash, a `.git` suffix, or the `ssh://` and `https://` scheme as different values. If your organization’s marketplace can be cloned by more than one URL form, prefer a `hostPattern` entry over a literal URL so the `https://`, `ssh://`, and `user@host:path` forms all match. Because `strictKnownMarketplaces` is set in [managed settings](</docs/en/managed-settings>), individual users and project configurations can’t override these restrictions. For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](</docs/en/settings-reference#strictknownmarketplaces>). ### @@ -1042,7 +1042,7 @@ To support “stable” and “latest” release channels for your plugins, you can set up two marketplaces that point to different refs or SHAs of the same repo. You can then give each user group its own marketplace through managed settings in one of two ways: - * Deploy separate [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>), such as a managed settings file or an MDM profile, to each group’s devices. On each device, Claude Code applies only the [highest-ranked managed source](</docs/en/managed-settings#precedence-within-the-managed-tier>) that delivers any keys, so this route works only when the per-group file or profile is that source on the group’s devices. + * Deploy separate [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>), such as a managed settings file or an MDM profile, to each group’s devices. [How Claude Code combines managed sources](</docs/en/managed-settings#precedence-within-the-managed-tier>) says whether the per-group file or profile applies on a device that also has an organization-wide source. * Define one [Claude apps gateway policy](</docs/en/claude-apps-gateway-config#managed>) per group. The gateway applies the first policy whose match rule fits a user, so order the policies so that each user reaches their group’s policy. A group policy’s `extraKnownMarketplaces` replaces the catch-all policy’s map rather than merging with it, so list every marketplace the group needs in the group’s policy, not only its channel marketplace. Server-managed settings from the admin console [apply to every user in your organization](</docs/en/server-managed-settings#current-limitations>), so they can’t carry a per-group assignment. @@ -1323,12 +1323,14 @@ `Invalid JSON syntax: Unexpected token...`| JSON syntax error in marketplace.json| Check for missing commas, extra commas, or unquoted strings `Duplicate plugin name "x" found in marketplace`| Two plugins share the same name| Give each plugin a unique `name` value `plugins[0].source: Path contains ".."`| Source path contains `..`| Use paths relative to the marketplace root without `..`. See Relative paths +`Marketplace name cannot contain control or bidirectional-formatting characters`| The marketplace `name` contains a Unicode bidirectional-formatting character or a control character, such as an escape or a newline| Remove the character from the name. Before v2.1.247, these characters produced the `Marketplace name impersonates an official Anthropic/Claude marketplace` error +`Plugin name cannot contain control or bidirectional-formatting characters`| A plugin `name` contains a Unicode bidirectional-formatting character or a control character, such as an escape or a newline| Remove the character from the name. Before v2.1.247, Claude Code didn’t run this check **Warnings** (non-blocking): * `Marketplace has no plugins defined`: add at least one plugin to the `plugins` array * `No marketplace description provided`: add a top-level `description` to help users understand your marketplace - * `Plugin name "x" is not kebab-case`: the plugin name contains uppercase letters, spaces, or special characters. Rename to lowercase letters, digits, and hyphens only (for example, `my-plugin`). Claude Code accepts other forms, but the claude.ai marketplace sync rejects them. + * `Plugin name "x" is not kebab-case`: rename to lowercase letters, digits, and hyphens only (for example, `my-plugin`). Claude Code accepts other forms, but the claude.ai marketplace sync rejects them. * `Marketplace name "x" is reserved in Claude Desktop`: the marketplace is named `org`, `org-provisioned`, or `unknown`, in any casing. Claude Code accepts these names, but Claude Desktop’s managed marketplace sync rejects the whole marketplace. Rename the marketplace. Before v2.1.221, `claude plugin validate` didn’t run this check. * `Marketplace name "x" is not accepted by Claude Desktop` or `Plugin name "x" is not accepted by Claude Desktop`: Claude Desktop accepts names of up to 128 characters made of letters, digits, `.`, `_`, and `-`, starting with a letter or digit. Claude Code accepts other forms, but Claude Desktop’s managed marketplace sync rejects a marketplace whose name fails the check and silently drops a plugin entry whose name does. Rename the marketplace or plugin. Before v2.1.221, `claude plugin validate` didn’t run these checks.
modified Recommend plugins for your org View current →
--- a/plugin-relevance.md +++ b/plugin-relevance.md @@ -1,4 +1,4 @@ -If you operate a plugin marketplace for your organization, you can have Claude Code suggest specific plugins to users based on what they are working on. Add a `relevance` block to a plugin’s entry in `marketplace.json`, then allowlist the marketplace in managed settings. When a user’s session matches one of the declared signals, Claude Code surfaces an install suggestion for that plugin. Marketplace-declared suggestions are opt-in per marketplace through [managed settings](</docs/en/managed-settings>). No marketplace’s `relevance` declarations produce suggestions until an administrator adds it to the allowlist, including the official Anthropic marketplace. Claude Code also includes one built-in suggestion that is independent of this allowlist; that tip and all marketplace-declared tips are disabled when [`spinnerTipsEnabled`](</docs/en/settings-reference#spinnertipsenabled>) is set to `false`. This feature requires Claude Code v2.1.152 or later. Older clients ignore the `relevance` field. This page is for marketplace operators and enterprise administrators. If you are looking to install plugins, see [Discover and install plugins](</docs/en/discover-plugins>). +If you operate a plugin marketplace for your organization, you can have Claude Code suggest specific plugins to users based on what they are working on. Add a `relevance` block to a plugin’s entry in `marketplace.json`, then allowlist the marketplace in managed settings. When a user’s session matches one of the declared signals, Claude Code surfaces an install suggestion for that plugin. Marketplace-declared suggestions are opt-in per marketplace through [managed settings](</docs/en/managed-settings>). No marketplace’s `relevance` declarations produce suggestions until an administrator adds it to the allowlist, including the official Anthropic marketplace. Claude Code also includes one built-in suggestion that is independent of this allowlist; that tip and all marketplace-declared tips are disabled when [`spinnerTipsEnabled`](</docs/en/settings-reference#spinnertipsenabled>) is set to `false`. This page is for marketplace operators and enterprise administrators. If you are looking to install plugins, see [Discover and install plugins](</docs/en/discover-plugins>). ##
modified Plugins reference View current →
--- a/plugins-reference.md +++ b/plugins-reference.md @@ -45,7 +45,17 @@ Detailed system prompt for the agent describing its role, expertise, and behavior. -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. 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. For complete details, see [Subagents](</docs/en/sub-agents>). +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. Claude Code loads a plugin agent even when its frontmatter has no `name` or doesn’t parse: + + * No `name`: Claude Code names the agent after the file, so `agents/reviewer.md` in a plugin named `my-plugin` loads as `my-plugin:reviewer` + * Frontmatter that doesn’t parse: Claude Code names the agent after the file, uses `Agent from my-plugin plugin` as its description, and ignores every field in the file + +By contrast, Claude Code skips a project, user, or managed agent file whose frontmatter has no `name` or doesn’t parse. To find files in a plugin’s default `agents/` directory whose frontmatter doesn’t parse, run `claude plugin validate`. The path you pass depends on whether the plugin has a manifest, and both examples use `./my-plugin` as the plugin directory: + + * A plugin with a manifest: `claude plugin validate ./my-plugin` + * A plugin without a manifest: `claude plugin validate ./my-plugin/agents`. Requires Claude Code v2.1.233 or later. + +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. For complete details, see [Subagents](</docs/en/sub-agents>). ### @@ -332,7 +342,7 @@ Personal-scope plugins have none of these restrictions. -Project-scope `@skills-dir` plugins load only from the `.claude/skills/` of the directory where you start Claude Code. They don’t [walk up to the repository root](</docs/en/skills#discovery-from-parent-and-nested-directories>) the way plain skills and commands do, so launching from a subdirectory misses a plugin that lives at the repo root. Launch from the repository root, or run `/reload-plugins` after changing directories. +Project-scope `@skills-dir` plugins load only from the `.claude/skills/` of the session’s [primary working directory](</docs/en/permissions#working-directories>). They don’t [walk up to the repository root](</docs/en/skills#discovery-from-parent-and-nested-directories>) the way plain skills and commands do, so launching from a subdirectory misses a plugin that lives at the repo root. Launch from the repository root, or [move the session there with `/cd`](</docs/en/permissions#move-the-session-to-another-directory>) on v2.1.246 or later. ### @@ -352,7 +362,7 @@ Plugins synced from claude.ai -In [Cowork](<https://claude.com/product/cowork>) and [cloud sessions](</docs/en/cloud-environments#what-carries-over-from-your-setup>), Claude Code downloads the plugins enabled for your claude.ai account into `~/.claude/plugins/synced/` in the session’s own environment and loads each one as `<name>@synced`, with no marketplace and no install record. Claude Code doesn’t load them in sessions you start in your own terminal. On a machine where a synced session has run, `claude plugin list` still shows the downloaded copies, under a `Synced from claude.ai` heading that notes they load only in a synced session. Before v2.1.239, Claude Code loaded these plugins as `<name>@inline`, the identity that `--plugin-dir` plugins use. Manage a synced plugin by the `<name>@synced` ID that `claude plugin list` prints: +In [Cowork](<https://claude.com/product/cowork>) and [cloud sessions](</docs/en/cloud-environments#what-carries-over-from-your-setup>), Claude Code downloads the plugins enabled for your claude.ai account into `~/.claude/plugins/synced/` in the session’s own environment and loads each one as `<name>@synced`, with no marketplace and no install record. Claude Code doesn’t load them in sessions you start in your own terminal. Inside that Cowork or cloud environment, `claude plugin list` shows the downloaded copies under a `Synced from claude.ai` heading. Before v2.1.239, Claude Code loaded these plugins as `<name>@inline`, the identity that `--plugin-dir` plugins use. Manage a synced plugin by the `<name>@synced` ID that `claude plugin list` prints: * **Turn one off** : in the synced session, run `claude plugin disable <name>@synced`, or ask Claude to run it. Claude Code saves the choice as `"<name>@synced": false` in that environment’s user-level [`enabledPlugins`](</docs/en/settings-reference#enabledplugins>). To turn the plugin back on, run `claude plugin enable <name>@synced` in the same session. To keep a plugin out of every synced session, [turn it off for your claude.ai account](</docs/en/desktop#extend-claude-code>). To keep it out of one project’s synced sessions in every environment, set `"<name>@synced": false` under `enabledPlugins` in that project’s committed `.claude/settings.json`. * **Manage the plugin itself on claude.ai** : `claude plugin install`, `update`, and `uninstall` don’t apply to a synced plugin. To remove one, turn the plugin off for your claude.ai account; the next synced session starts without it. @@ -417,7 +427,7 @@ Field| Type| Description| Example ---|---|---|--- -`name`| string| Unique identifier (kebab-case, no spaces). When a [marketplace entry](</docs/en/plugin-marketplaces#plugin-entries>) lists the plugin under a different name, the marketplace entry name is what `enabledPlugins` keys and `/plugin` use| `"deployment-tools"` +`name`| string| Unique identifier in kebab-case, with no spaces, control characters, or bidirectional-formatting characters. When a [marketplace entry](</docs/en/plugin-marketplaces#plugin-entries>) lists the plugin under a different name, the marketplace entry name is what `enabledPlugins` keys and `/plugin` use| `"deployment-tools"` This name is used for namespacing components. For example, in the UI, the agent `agent-creator` for the plugin with name `plugin-dev` will appear as `plugin-dev:agent-creator`. @@ -454,7 +464,7 @@ `license`| string| License identifier| `"MIT"`, `"Apache-2.0"` `keywords`| array| Discovery tags| `["deployment", "ci-cd"]` `metadata`| object| Free-form object for your own data, such as entitlement or catalog fields. Claude Code doesn’t read it, so the values never affect plugin behavior. Claude Code ignores a non-object value, and `claude plugin validate` reports it as a warning. Before v2.1.222, Claude Code treated the key as an unrecognized field.| `{"catalogId": "cat-123"}` -`defaultEnabled`| boolean| Whether the plugin starts in an enabled state when the user has not set one. Defaults to `true`. See Default enablement. Requires Claude Code v2.1.154 or later.| `false` +`defaultEnabled`| boolean| Whether the plugin starts in an enabled state when the user has not set one. Defaults to `true`. See Default enablement.| `false` ### @@ -462,7 +472,7 @@ Default enablement -Set `defaultEnabled: false` in `plugin.json` to ship a plugin that installs disabled. The user turns it on with `claude plugin enable <plugin>` or the `/plugin` interface. Use this for plugins that add cost or scope a user should opt into, such as one that connects to an external service. This requires Claude Code v2.1.154 or later. Earlier versions ignore the field and enable the plugin on install. `defaultEnabled` is the fallback when nothing else has decided the plugin’s state. Two things take precedence over it: +Set `defaultEnabled: false` in `plugin.json` to ship a plugin that installs disabled. The user turns it on with `claude plugin enable <plugin>` or the `/plugin` interface. Use this for plugins that add cost or scope a user should opt into, such as one that connects to an external service. `defaultEnabled` is the fallback when nothing else has decided the plugin’s state. Two things take precedence over it: * **The user’s setting** : an entry for the plugin in `enabledPlugins` at any settings scope. Once written, it persists across plugin updates and reinstalls, so changing `defaultEnabled` in a later release does not flip an existing user. * **A dependency requirement** : when a plugin is required by another one that is active, Claude Code writes `true` for it at install or enable time. That gives it an explicit setting, so its own default no longer applies. See [Enable or disable a plugin with dependencies](</docs/en/plugin-dependencies#enable-or-disable-a-plugin-with-dependencies>). @@ -989,7 +999,7 @@ plugin enable -Enable a disabled plugin. If the plugin declares [dependencies](</docs/en/plugin-dependencies>), Claude Code enables them transitively at the same scope, and the command fails when a dependency is not installed. +Enable a disabled plugin. When the target is installed from a marketplace and declares [dependencies](</docs/en/plugin-dependencies>), Claude Code enables them transitively at the same scope. The command fails under the conditions that [Enable or disable a plugin with dependencies](</docs/en/plugin-dependencies#enable-or-disable-a-plugin-with-dependencies>) lists. claude plugin enable <plugin> [options] @@ -1010,7 +1020,7 @@ plugin disable -Disable a plugin without uninstalling it. Fails when another enabled plugin [depends on](</docs/en/plugin-dependencies#enable-or-disable-a-plugin-with-dependencies>) the target. The error message includes a chained command that disables every dependent first. +Disable a plugin without uninstalling it. When the target is installed from a marketplace, the command fails if another enabled plugin [depends on](</docs/en/plugin-dependencies#enable-or-disable-a-plugin-with-dependencies>) it. The error message includes a chained command that disables every dependent first. claude plugin disable [plugin] [options] @@ -1073,7 +1083,7 @@ Within an interactive session, `/plugin list` prints a similar listing inline, but it covers marketplace-installed plugins only: * Plugins loaded from skills directories appear in the `/plugin` interface and in `claude plugin list`, but not in the inline `/plugin list` output. - * On Claude Code v2.1.239 or later, plugins synced from claude.ai appear in `claude plugin list` on any machine where a synced session has downloaded them, with a note that they load only in a synced session. They don’t appear in the inline `/plugin list` output. + * On Claude Code v2.1.239 or later, plugins synced from claude.ai appear in `claude plugin list` when you run it in the environment where a synced session downloaded them. They don’t appear in the inline `/plugin list` output. * Plugins loaded for the session with `--plugin-dir` or `--plugin-url` appear in the `/plugin` interface, and in `claude plugin list` only when the same flag precedes the subcommand, as in `claude --plugin-dir <dir> plugin list`. Only the flag names their location, so a bare `claude plugin list` can’t find them, unlike synced plugins and skills-directory plugins, whose fixed directories Claude Code scans. The interactive form accepts `--enabled` or `--disabled` to show only plugins in that state, and `ls` as a shorthand for `list`.
modified How Claude Code uses prompt caching View current →
--- a/prompt-caching.md +++ b/prompt-caching.md @@ -139,10 +139,11 @@ When plugin changes apply -Claude Code applies a plugin change when you run [`/reload-plugins`](</docs/en/discover-plugins#apply-plugin-changes-without-restarting>) or start a new session. You pay the cost, whether appended announcements or a full re-read, on the first turn after the change applies, not when you run `/plugin enable` or `/plugin disable`. Claude Code can also apply a change on its own in two cases: +Claude Code applies a plugin change when you run [`/reload-plugins`](</docs/en/discover-plugins#apply-plugin-changes-without-restarting>) or start a new session. You pay the cost, whether appended announcements or a full re-read, on the first turn after the change applies, not when you run `/plugin enable` or `/plugin disable`. Claude Code can also apply a change on its own in three cases: * For a plugin with a `command` source, Claude Code [can reload the plugin itself](</docs/en/plugin-marketplaces#when-claude-code-re-runs-the-command>). * When you [install a plugin from the `/plugin` interface](</docs/en/discover-plugins#install-plugins>), Claude Code can activate it during the install. Claude Code tells you in the install summary whether it did or whether to run `/reload-plugins`. + * When you [move the session with `/cd`](</docs/en/permissions#move-the-session-to-another-directory>) on v2.1.246 or later, Claude Code applies the plugins the new directory’s settings enable as part of the move, without the full re-read warning that holds a `/reload-plugins`. When you run `/reload-plugins` and the reload would trigger a full re-read, Claude Code shows a warning and doesn’t apply the reload. Rerun it with `--force` to apply the reload anyway. @@ -302,7 +303,7 @@ 4. `ENABLE_PROMPT_CACHING_1H=1`, which requests one hour for both buckets 5. The default for the request’s bucket -Set `FORCE_PROMPT_CACHING_5M=1` when you’re debugging cache behavior, comparing the two TTLs, or overriding a longer TTL set in [managed settings](</docs/en/managed-settings>). The one-hour TTL isn’t available through the [Claude apps gateway](</docs/en/claude-apps-gateway#availability-and-limitations>). On Amazon Bedrock, prompt caching support, minimum cacheable prefix length, and one-hour TTL availability all vary by model. If cache token counts stay at zero, check [supported models, regions, and limits](<https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html#prompt-caching-models>) in the Amazon Bedrock documentation. +Set `FORCE_PROMPT_CACHING_5M=1` when you’re debugging cache behavior, comparing the two TTLs, or overriding a longer TTL set in [managed settings](</docs/en/managed-settings>). To confirm which TTL your main conversation’s cache writes used, run `claude -p "hello" --output-format json` and read `usage.cache_creation` in the result. Claude Code reports one-hour cache writes under `ephemeral_1h_input_tokens` and five-minute cache writes under `ephemeral_5m_input_tokens`. Through an LLM gateway you set with `ANTHROPIC_BASE_URL`, part of the one-hour request travels in the `anthropic-beta` header, so configure the gateway to [forward that header unchanged](</docs/en/llm-gateway-protocol#request-headers>). The one-hour TTL isn’t available through the [Claude apps gateway](</docs/en/claude-apps-gateway#availability-and-limitations>). On Amazon Bedrock, prompt caching support, minimum cacheable prefix length, and one-hour TTL availability all vary by model. If cache token counts stay at zero, check [supported models, regions, and limits](<https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html#prompt-caching-models>) in the Amazon Bedrock documentation. ##
modified Agent SDK reference - Python View current →
Show diff (302 lines)
--- a/python.md +++ b/python.md @@ -2022,6 +2022,8 @@ Error Types +The types below define what your code catches. For entries keyed to the error messages these types raise, with the cause and fix for each, see [Troubleshooting](</docs/en/agent-sdk/troubleshooting>). + ### ​ @@ -2163,11 +2165,7 @@ * `tool_use_id`: Optional tool use identifier (for tool-related hooks) * `context`: Hook context with additional information -Returns a `HookJSONOutput` that may contain: - - * `decision`: `"block"` to block the action - * `systemMessage`: warning message shown to the user - * `hookSpecificOutput`: Hook-specific output data +Returns a `HookJSONOutput`. ### @@ -3042,7 +3040,7 @@ **Tool name:** `TodoWrite` -On Python Agent SDK 0.2.139 and later, the following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in: +On Python Agent SDK 0.2.139 and later, the following restriction applies.The following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in: * `TodoWrite` * `TaskCreate` @@ -3290,13 +3288,9 @@ ​ -Advanced Features with ClaudeSDKClient - -### - -​ - -Building a Continuous Conversation Interface +Build a continuous conversation interface + +The following example keeps one `ClaudeSDKClient` connected across turns, so Claude remembers earlier messages. Type `new` to disconnect and reconnect for a fresh session, or `exit` to end the conversation. from claude_agent_sdk import ( ClaudeSDKClient, @@ -3370,166 +3364,13 @@ asyncio.run(main()) -### - -​ - -Using Hooks for Behavior Modification - - from claude_agent_sdk import ( - ClaudeSDKClient, - ClaudeAgentOptions, - HookMatcher, - HookContext, - ) - import asyncio - from typing import Any - - async def pre_tool_logger( - input_data: dict[str, Any], tool_use_id: str | None, context: HookContext - ) -> dict[str, Any]: - """Log all tool usage before execution.""" - tool_name = input_data.get("tool_name", "unknown") - print(f"[PRE-TOOL] About to use: {tool_name}") - - # You can modify or block the tool execution here - if tool_name == "Bash" and "rm -rf" in str(input_data.get("tool_input", {})): - return { - "hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": "deny", - "permissionDecisionReason": "Dangerous command blocked", - } - } - return {} - - async def post_tool_logger( - input_data: dict[str, Any], tool_use_id: str | None, context: HookContext - ) -> dict[str, Any]: - """Log results after tool execution.""" - tool_name = input_data.get("tool_name", "unknown") - print(f"[POST-TOOL] Completed: {tool_name}") - return {} - - async def user_prompt_modifier( - input_data: dict[str, Any], tool_use_id: str | None, context: HookContext - ) -> dict[str, Any]: - """Add context to user prompts.""" - original_prompt = input_data.get("prompt", "") - - # Add a timestamp as additional context for Claude to see - from datetime import datetime - - timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - - return { - "hookSpecificOutput": { - "hookEventName": "UserPromptSubmit", - "additionalContext": f"[Submitted at {timestamp}] Original prompt: {original_prompt}", - } - } - - async def main(): - options = ClaudeAgentOptions( - hooks={ - "PreToolUse": [ - HookMatcher(hooks=[pre_tool_logger]), - HookMatcher(matcher="Bash", hooks=[pre_tool_logger]), - ], - "PostToolUse": [HookMatcher(hooks=[post_tool_logger])], - "UserPromptSubmit": [HookMatcher(hooks=[user_prompt_modifier])], - }, - allowed_tools=["Read", "Write", "Bash"], - ) - - async with ClaudeSDKClient(options=options) as client: - await client.query("List files in current directory") - - async for message in client.receive_response(): - # Hooks will automatically log tool usage - pass - - asyncio.run(main()) - -### - -​ - -Real-time Progress Monitoring - - from claude_agent_sdk import ( - ClaudeSDKClient, - ClaudeAgentOptions, - AssistantMessage, - ToolUseBlock, - ToolResultBlock, - TextBlock, - ) - import asyncio - - async def monitor_progress(): - options = ClaudeAgentOptions( - allowed_tools=["Write", "Bash"], permission_mode="acceptEdits" - ) - - async with ClaudeSDKClient(options=options) as client: - await client.query("Create 5 Python files with different sorting algorithms") - - # Monitor progress in real-time - async for message in client.receive_response(): - if isinstance(message, AssistantMessage): - for block in message.content: - if isinstance(block, ToolUseBlock): - if block.name == "Write": - file_path = block.input.get("file_path", "") - print(f"Creating: {file_path}") - elif isinstance(block, ToolResultBlock): - print("Completed tool execution") - elif isinstance(block, TextBlock): - print(f"Claude says: {block.text[:100]}...") - - print("Task completed!") - - asyncio.run(monitor_progress()) - ## ​ -Example Usage - -### - -​ - -Basic file operations (using query) - - from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock - import asyncio - - async def create_project(): - options = ClaudeAgentOptions( - allowed_tools=["Read", "Write", "Bash"], - permission_mode="acceptEdits", - ) - - async for message in query( - prompt="Create a Python project structure with setup.py", options=options - ): - if isinstance(message, AssistantMessage): - for block in message.content: - if isinstance(block, ToolUseBlock): - print(f"Using tool: {block.name}") - - asyncio.run(create_project()) - -### - -​ - Error handling -This example catches `ResultError`, which requires Python Agent SDK 0.2.140 or later. +The following example wraps a `query()` call in handlers for four of the error types the SDK raises. This example catches `ResultError`, which requires Python Agent SDK 0.2.140 or later. import asyncio @@ -3564,76 +3405,6 @@ asyncio.run(main()) -### - -​ - -Using custom tools with ClaudeSDKClient - - from claude_agent_sdk import ( - ClaudeSDKClient, - ClaudeAgentOptions, - tool, - create_sdk_mcp_server, - AssistantMessage, - TextBlock, - ) - import asyncio - from typing import Any - - # Define custom tools with @tool decorator - @tool("calculate", "Perform mathematical calculations", {"expression": str}) - async def calculate(args: dict[str, Any]) -> dict[str, Any]: - try: - result = eval(args["expression"], {"__builtins__": {}}) - return {"content": [{"type": "text", "text": f"Result: {result}"}]} - except Exception as e: - return { - "content": [{"type": "text", "text": f"Error: {str(e)}"}], - "is_error": True, - } - - @tool("get_time", "Get current time", {}) - async def get_time(args: dict[str, Any]) -> dict[str, Any]: - from datetime import datetime - - current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - return {"content": [{"type": "text", "text": f"Current time: {current_time}"}]} - - async def main(): - # Create SDK MCP server with custom tools - my_server = create_sdk_mcp_server( - name="utilities", version="1.0.0", tools=[calculate, get_time] - ) - - # Configure options with the server - options = ClaudeAgentOptions( - mcp_servers={"utils": my_server}, - allowed_tools=["mcp__utils__calculate", "mcp__utils__get_time"], - ) - - # Use ClaudeSDKClient for interactive tool usage - async with ClaudeSDKClient(options=options) as client: - await client.query("What's 123 * 456?") - - # Process calculation response - async for message in client.receive_response(): - if isinstance(message, AssistantMessage): - for block in message.content: - if isinstance(block, TextBlock): - print(f"Calculation: {block.text}") - - # Follow up with time query - await client.query("What time is it now?") - - async for message in client.receive_response(): - if isinstance(message, AssistantMessage): - for block in message.content: - if isinstance(block, TextBlock): - print(f"Time: {block.text}") - - asyncio.run(main()) - ## ​ @@ -3826,5 +3597,6 @@ * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts * [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) \- TypeScript SDK documentation + * [Custom tools](</docs/en/agent-sdk/custom-tools>) \- Define in-process MCP tools for Claude to call * [CLI reference](</docs/en/cli-reference>) \- Command-line interface * [Common workflows](</docs/en/common-workflows>) \- Step-by-step guides
modified Quickstart View current →
--- a/quickstart.md +++ b/quickstart.md @@ -229,7 +229,7 @@ This is what makes the Agent SDK different: Claude executes tools directly instead of asking you to implement them. -If you see “API key not found”, make sure you’ve set the `ANTHROPIC_API_KEY` environment variable in the shell where you run your agent. The SDK doesn’t load `.env` files automatically. See the [full troubleshooting guide](</docs/en/troubleshooting>) for more help. +If you see an authentication error such as `Not logged in` or `Invalid API key`, make sure you’ve set the `ANTHROPIC_API_KEY` environment variable in the shell where you run your agent. The SDK doesn’t load `.env` files automatically. See the [full troubleshooting guide](</docs/en/troubleshooting>) for more help. ### @@ -335,3 +335,4 @@ * **[MCP servers](</docs/en/agent-sdk/mcp>)** : connect to databases, browsers, APIs, and other external systems * **[Hosting](</docs/en/agent-sdk/hosting>)** : deploy agents to Docker, cloud, and CI/CD * **[Example agents](<https://github.com/anthropics/claude-agent-sdk-demos>)** : see complete examples: email assistant, research agent, and more + * **[Troubleshooting](</docs/en/agent-sdk/troubleshooting>)** : fix Agent SDK errors by the exact message you see
modified Automate work with routines View current →
--- a/routines.md +++ b/routines.md @@ -22,7 +22,7 @@ Create a routine -Create a routine from the web at [claude.ai/code/routines](<https://claude.ai/code/routines>), from the Desktop app, or from the CLI. All three surfaces write to the same cloud account, so a routine you create in one shows up in the others immediately. In the Desktop app’s **Code** tab, click **Routines** in the sidebar, then **New routine** , and choose **Cloud** ; choosing **Local** instead creates a [Desktop scheduled task](</docs/en/desktop-scheduled-tasks>), which runs on your machine rather than in the cloud. If **Routines** is missing from the Desktop sidebar, routines aren’t available to your account; see “Routines are disabled by your organization’s policy”. The creation form sets up the routine’s prompt, repositories, environment, connectors, and triggers. Routines run autonomously as full Claude Code cloud sessions: there is no permission-mode picker and no approval prompts during a run. The session can run shell commands, use [skills](</docs/en/skills>) committed to the cloned repository, and call any connectors you include. What a routine can reach is determined by the repositories you select, the [environment’s](</docs/en/cloud-environments>) network access and variables, and the connectors you include. Scope each of those to what the routine actually needs. Routines belong to your individual claude.ai account. They are not shared with teammates, and they count against your account’s daily run allowance. Anything a routine does through your connected GitHub identity or connectors appears as you: commits and pull requests carry your GitHub user, and Slack messages, Linear tickets, or other connector actions use your linked accounts for those services. +Create a routine from the web at [claude.ai/code/routines](<https://claude.ai/code/routines>), from the Desktop app, or from the CLI. All three surfaces write to the same cloud account, so a routine you create in one shows up in the others immediately. In the Desktop app’s **Code** tab, click **Routines** in the sidebar, then **New routine** , and choose **Cloud** ; choosing **Local** instead creates a [Desktop scheduled task](</docs/en/desktop-scheduled-tasks>), which runs on your machine rather than in the cloud. If **Routines** is missing from the Desktop sidebar, routines aren’t available to your account: they need a Pro, Max, Team, or Enterprise plan with Claude Code on the web enabled, and on Team and Enterprise plans an Owner can turn them off with the Routines toggle at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>). The creation form sets up the routine’s prompt, repositories, environment, connectors, and triggers. Routines run autonomously as full Claude Code cloud sessions: there is no permission-mode picker and no approval prompts during a run. The session can run shell commands, use [skills](</docs/en/skills>) committed to the cloned repository, and call any connectors you include. What a routine can reach is determined by the repositories you select, the [environment’s](</docs/en/cloud-environments>) network access and variables, and the connectors you include. Scope each of those to what the routine actually needs. Routines belong to your individual claude.ai account. They are not shared with teammates, and they count against your account’s daily run allowance. Anything a routine does through your connected GitHub identity or connectors appears as you: commits and pull requests carry your GitHub user, and Slack messages, Linear tickets, or other connector actions use your linked accounts for those services. ### @@ -319,7 +319,7 @@ Repositories and branch permissions -Routines need GitHub access to clone repositories. When you create a routine from the CLI with `/schedule`, Claude checks whether your account has GitHub connected and prompts you to run `/web-setup` if it doesn’t. See [GitHub authentication options](</docs/en/claude-code-on-the-web#github-authentication-options>) for the two ways to grant access. Each repository you add is cloned on every run. Claude starts from the repository’s default branch unless your prompt specifies otherwise. Claude pushes its work to branches prefixed with `claude/`, which are always accepted. When your prompt directs Claude to push to another branch, Claude Code checks the push first and rejects it if any of the following is true: +Routines need GitHub access to clone repositories. When you create a routine from the CLI with `/schedule`, Claude checks whether your account has GitHub access for the repository you ran it from and, if it doesn’t, adds a setup note naming how to grant it. See [GitHub authentication options](</docs/en/claude-code-on-the-web#github-authentication-options>) for the two ways to grant access. Each repository you add is cloned on every run. Claude starts from the repository’s default branch unless your prompt specifies otherwise. Claude pushes its work to branches prefixed with `claude/`, which are always accepted. When your prompt directs Claude to push to another branch, Claude Code checks the push first and rejects it if any of the following is true: * The branch is protected on GitHub * Someone else has an open pull request from that branch
modified Configure the sandboxed Bash tool View current →
--- a/sandboxing.md +++ b/sandboxing.md @@ -151,7 +151,7 @@ } } -These paths are enforced at the OS level, so all commands running inside the sandbox, including their child processes, respect them. This is the recommended approach when a tool needs write access to a specific location, rather than excluding the tool from the sandbox entirely with `excludedCommands`. When the same filesystem array is defined in multiple [settings scopes](</docs/en/settings#settings-precedence>), the arrays are merged: paths from every scope are combined, not replaced. When you edit these lists during a session, Claude Code [applies the change to the running session](</docs/en/settings#when-edits-take-effect>), so the next sandboxed command runs under the new paths. Path prefixes control how paths are resolved: +These paths are enforced at the OS level, so all commands running inside the sandbox, including their child processes, respect them. This is the recommended approach when a tool needs write access to a specific location, rather than excluding the tool from the sandbox entirely with `excludedCommands`. When you define the same filesystem array in multiple [settings scopes](</docs/en/settings#settings-precedence>), Claude Code merges them, combining paths from every scope rather than replacing one scope’s array with another’s. If you exclude a source with [`--setting-sources`](</docs/en/cli-reference>) on the CLI or [`settingSources`](</docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources>) in the Agent SDK, Claude Code ignores its `sandbox.filesystem` entries, its `Edit` permission rules, and its `Read` deny rules when building the sandbox configuration. Requires Claude Code v2.1.246 or later. When you edit these filesystem lists during a session, Claude Code [applies the change to the running session](</docs/en/settings#when-edits-take-effect>), so the next sandboxed command runs under the new paths. Path prefixes control how paths are resolved: Prefix| Meaning| Example ---|---|--- @@ -271,7 +271,12 @@ } } -Environment variable entries and file entries also accept `"mode": "mask"`, described under Mask credentials. File paths follow the same [prefix rules](</docs/en/settings-reference#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>). +Environment variable entries and file entries also accept `"mode": "mask"`, described under Mask credentials. File paths follow the same [prefix rules](</docs/en/settings-reference#sandbox-path-prefixes>) as `sandbox.filesystem.*` settings. Claude Code merges the `deny` entries from every [settings scope](</docs/en/settings#settings-precedence>) the session loads. A `deny` entry only ever narrows access, so any scope can add one, but no scope can remove one that another scope added. When you exclude a settings source: + + * **Project or local settings** : Claude Code applies none of their `credentials` entries. Requires Claude Code v2.1.246 or later. + * **User settings** : Claude Code still applies the `deny` entries in `~/.claude/settings.json` and keeps its file `mask` entries as restrictions, but drops its environment variable `mask` entries. + +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>). ### @@ -310,7 +315,7 @@ * **`network.allowedDomains`** : the bracketed form domain lists use, such as `"[::1]"`. The proxy checks this list to admit the connection. * **`injectHosts`** : the bare address in its canonical compressed form, such as `"::1"` or `"2001:db8::1"`. The proxy matches each entry against the connection’s bare destination address, ignoring ports, so a bracketed, zone-ID, or differently compressed spelling never matches and the proxy never injects the credential there. -`/doctor` flags `injectHosts` entries that can never match with the warning `Sandbox credential injectHosts entries can never match their destination`. 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-reference#sandbox-credentials-allowplaintextinject>), which lets the proxy inject credentials into unencrypted requests, are all ignored in a repository’s `.claude/settings.json` or `.claude/settings.local.json`. When the same variable is listed with `deny` in any scope, `deny` takes precedence. Masking replaces the variable’s entire value by default, which suits a bare token. Optional entry fields, which require Claude Code v2.1.224 or later, handle values with structure: +`/doctor` flags `injectHosts` entries that can never match with the warning `Sandbox credential injectHosts entries can never match their destination`. Unlike `deny`, masking authorizes the proxy to send your real credential to the listed hosts, so Claude Code honors it only from settings you or your administrator control: user settings, managed settings, and the `--settings` CLI flag. Claude Code ignores `mask` entries in a repository’s `.claude/settings.json` or `.claude/settings.local.json`. In those files it also ignores `network.tlsTerminate` and [`credentials.allowPlaintextInject`](</docs/en/settings-reference#sandbox-credentials-allowplaintextinject>), the setting that lets the proxy inject credentials into unencrypted requests. If you exclude user settings, Claude Code drops the environment variable `mask` entries in `~/.claude/settings.json` too. When the same variable is listed with `deny` in any scope, `deny` takes precedence. Masking replaces the variable’s entire value by default, which suits a bare token. Optional entry fields, which require Claude Code v2.1.224 or later, handle values with structure: * `extract`: a regular expression Claude Code applies across the value, replacing only the text captured by group 1 of each match, so a tool that parses the value, such as a `DATABASE_URL` connection string, still works inside the sandbox. The pattern must contain at least one capturing group. * `onExtractNoMatch` controls what happens when the pattern matches nothing: @@ -369,7 +374,7 @@ * **Linux and WSL2** : sandboxed commands read a sentinel copy of the file, a stand-in whose secret is replaced with a placeholder value, and the sandbox proxy substitutes the real value on egress. * **macOS** : sandboxed commands can’t read the listed file at all. Claude Code builds no sentinel copy and substitutes nothing on egress, so tools that authenticate with the file don’t work inside the sandbox, the same effect as `deny`. Unlike a `deny` entry, the read block holds even when you disable filesystem isolation. -On every platform, the [`network.tlsTerminate`](</docs/en/settings-reference#sandbox-network-tlsterminate>) requirement, `injectHosts`, and the settings-source restriction work the same way as for masked environment variables. The example below masks a GitHub token stored in `~/.config/gh/hosts.yml`; the `extract` pattern, covered below, tells Claude Code which part of the file is the secret. On Linux and WSL2, sandboxed commands that read the file get a sentinel in place of the token, and the proxy substitutes the real token on requests to `api.github.com`: +On every platform, Claude Code applies the [`network.tlsTerminate`](</docs/en/settings-reference#sandbox-network-tlsterminate>) requirement and `injectHosts` the same way as for masked environment variables, and ignores repository settings the same way. If you exclude user settings, Claude Code keeps the file `mask` entries in `~/.claude/settings.json` as restrictions, but the entries no longer authorize the proxy to substitute the real value. The example below masks a GitHub token stored in `~/.config/gh/hosts.yml`; the `extract` pattern, covered below, tells Claude Code which part of the file is the secret. On Linux and WSL2, sandboxed commands that read the file get a sentinel in place of the token, and the proxy substitutes the real token on requests to `api.github.com`: { "sandbox": { @@ -573,7 +578,7 @@ Keep developers from widening the policy -For boolean keys such as `enabled` and `failIfUnavailable`, Claude Code uses the managed value and ignores anything a developer sets locally. For array keys such as `excludedCommands` and `allowRead`, Claude Code merges entries from every scope, so a developer can append entries that widen the policy. Set `allowManagedReadPathsOnly` to `true` in managed settings so that only `allowRead` entries from managed settings are honored. User, project, and local `allowRead` entries are ignored. This prevents developers from widening read access beyond the organization-approved paths. To lock network domains to the managed values the same way, set [`allowManagedDomainsOnly`](</docs/en/settings-reference#sandbox-network-allowmanageddomainsonly>). When managed settings configure `sandbox.filesystem` or list any `sandbox.credentials.files` entry with `"mode": "deny"`, only managed settings can set `filesystem.disabled`, so developers can’t switch off administrator-deployed filesystem restrictions. Whether a `mask` entry pins the key depends on how it resolves; the table under Which settings can disable it covers the four cases. `excludedCommands` has no equivalent managed-only lockdown, so a developer can always append entries that run additional commands outside the sandbox. Keep the managed list narrow. +For boolean keys such as `enabled` and `failIfUnavailable`, Claude Code uses the managed value and ignores anything a developer sets locally. For array keys such as `excludedCommands` and `allowRead`, Claude Code merges entries from every scope the session loads, so a developer can append entries that widen the policy. Set `allowManagedReadPathsOnly` to `true` in managed settings so that only `allowRead` entries from managed settings are honored. This prevents developers from widening read access beyond the organization-approved paths. To lock network domains to the managed values the same way, set [`allowManagedDomainsOnly`](</docs/en/settings-reference#sandbox-network-allowmanageddomainsonly>). When managed settings configure `sandbox.filesystem` or list any `sandbox.credentials.files` entry with `"mode": "deny"`, only managed settings can set `filesystem.disabled`, so developers can’t switch off administrator-deployed filesystem restrictions. Whether a `mask` entry pins the key depends on how it resolves; the table under Which settings can disable it covers the four cases. `excludedCommands` has no equivalent managed-only lockdown, so a developer can always append entries that run additional commands outside the sandbox. Keep the managed list narrow. ###
modified Run prompts on a schedule View current →
--- a/scheduled-tasks.md +++ b/scheduled-tasks.md @@ -65,9 +65,9 @@ /loop check whether CI passed and address any review comments -When you ask for a dynamic `/loop` schedule, Claude may use the [Monitor tool](</docs/en/tools-reference#monitor-tool>) directly. Monitor runs a background script and streams each output line back, which avoids polling altogether and is often more token-efficient and responsive than re-running a prompt on an interval. A dynamically scheduled loop appears in your scheduled task list like any other task, so you can list or cancel it the same way. The jitter rules don’t apply to it, but the seven-day expiry does. - -On Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, and Microsoft Foundry, `/loop` behaves differently in two ways: a prompt with no interval runs on a fixed 10-minute schedule instead of a schedule Claude chooses, and `/loop` with no prompt prints the usage message instead of running the maintenance prompt or reading `loop.md`. The same happens when you turn off [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>). +In a session where the [Monitor tool is available](</docs/en/tools-reference#monitor-tool>), Claude may use it directly when you ask for a dynamic `/loop` schedule. Monitor runs a background script and streams each output line back, which avoids polling altogether and is often more token-efficient and responsive than re-running a prompt on an interval. A dynamically scheduled loop appears in your scheduled task list like any other task, so you can list or cancel it the same way. The jitter rules don’t apply to it, but the seven-day expiry does. + +Dynamically chosen intervals and the built-in maintenance prompt work on every provider, and with [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>) turned off. On Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, and Microsoft Foundry, or with fetching turned off, both require Claude Code v2.1.248 or later. In those cases, on earlier versions, a prompt with no interval runs on a fixed 10-minute schedule, and a `/loop` with no prompt prints the usage message. ### @@ -93,7 +93,7 @@ Customize the default prompt with loop.md -Where the built-in maintenance prompt is available, a `loop.md` file replaces it with your own instructions. It defines a single default prompt for bare `/loop`, not a list of separate scheduled tasks, and is ignored whenever you supply a prompt on the command line. To schedule additional prompts alongside it, use `/loop <prompt>` or ask Claude directly. Claude looks for the file in two locations and uses the first one it finds. +Create a `loop.md` file to replace the built-in maintenance prompt with your own instructions. It defines a single default prompt for bare `/loop`, not a list of separate scheduled tasks, and Claude Code ignores it whenever you supply a prompt on the command line. To schedule additional prompts alongside it, use `/loop <prompt>` or ask Claude directly. Claude looks for the file in two locations and uses the first one it finds. Path| Scope ---|--- @@ -117,7 +117,7 @@ Stop a loop -To stop a `/loop` while it is waiting for the next iteration, press `Esc`. This clears the pending wakeup so the loop does not fire again. Tasks you scheduled by asking Claude directly are not affected by `Esc` and stay in place until you delete them. In self-paced mode, Claude can also end the loop on its own once the task is complete. Claude calls the [`ScheduleWakeup` tool](</docs/en/tools-reference>) with `stop: true`, which cancels the pending wakeup immediately. If an iteration ends without either rescheduling or stopping, Claude Code schedules one fallback wakeup about 20 minutes later and ends the loop when that iteration doesn’t reschedule either. Loops on a fixed interval keep running until you stop them or seven days elapse. +To stop a self-paced `/loop` while it is waiting for the next iteration, press `Esc`. This clears the pending wakeup so the loop does not fire again. Tasks you scheduled by asking Claude directly are not affected by `Esc` and stay in place until you delete them. In self-paced mode, Claude can also end the loop on its own once the task is complete. Claude calls the [`ScheduleWakeup` tool](</docs/en/tools-reference>) with `stop: true`, which cancels the pending wakeup immediately. If an iteration ends without either rescheduling or stopping, Claude Code schedules one fallback wakeup about 20 minutes later and ends the loop when that iteration doesn’t reschedule either. Loops on a fixed interval keep running until you cancel them like any other scheduled task or seven days elapse. ## @@ -222,7 +222,7 @@ * Tasks only fire while Claude Code is running and idle. Closing the terminal or letting the session exit stops them firing. [Backgrounding the session](</docs/en/agent-view#from-inside-a-session>) carries `/loop` tasks over to a background session, which keeps running without a terminal. * No catch-up for missed fires. If a task’s scheduled time passes while Claude is busy on a long-running request, it fires once when Claude becomes idle, not once per missed interval. * Starting a fresh conversation clears all session-scoped tasks. Resuming with `claude --resume` or `claude --continue` restores recurring tasks that have not expired and one-shot tasks whose scheduled time has not yet passed. Background Bash and monitor tasks are never restored on resume. - * Claude Code stores the scheduled task list in the project’s `.claude` directory, and scheduling a task fails with an error when that directory, or the task file inside it, is a symlink. + * With [feature-flag fetching off](</docs/en/env-vars#features-that-need-feature-flag-fetching>), Claude Code stores a task you asked to keep across sessions in the project’s `.claude` directory. When that directory or the task file in it is a symlink, Claude Code returns an error instead of scheduling the task. For cron-driven automation that needs to run unattended:
modified Self-hosted environments View current →
--- a/self-hosted-environments.md +++ b/self-hosted-environments.md @@ -16,7 +16,7 @@ When a developer starts a cloud session, the session-start UI shows an environment picker listing Anthropic-hosted environments alongside any your organization has created. If they choose yours, Anthropic’s control plane places the session on your environment’s queue, where a runner claims it, clones the repository the developer chose, and starts a Claude Code process on your host to run it. The runner authenticates to your git host with credentials you configure; [Configure git](</docs/en/self-hosted-environments-deploy#configure-git>) covers the options. Sessions reach your internal services from inside your network, and your git host the same way when it’s internal; the traffic to Anthropic, queue polling, the session’s event stream, and model inference, is outbound HTTPS to `api.anthropic.com`, with the short list of further hosts sessions can reach in [Network requirements](</docs/en/self-hosted-environments-deploy#network-requirements>). Anthropic never connects into your network. -The two Claude Code boxes in the diagram are session processes: one runner executing two sessions at once, up to its configured capacity. A runner serves one user at a time, locking to that user’s account when it claims its first session, so checked-out code never mixes between users; Runner lifecycle covers the rule. You can start runners yourself and keep them running, or run the [autoscaling orchestrator](</docs/en/self-hosted-environments-configuration#on-demand-runners>), a second process you host, which starts runners as sessions queue; each runner exits on its own when its work finishes. Either way, you set the environment up once, and it appears in the picker on every supported surface. +The two Claude Code boxes in the diagram are session processes: one runner executing two sessions at once, up to its configured capacity. A runner serves one owner at a time and locks to that owner when it claims its first session, so checked-out code never mixes between owners; Runner lifecycle covers the rule. You can start runners yourself and keep them running, or run the [autoscaling orchestrator](</docs/en/self-hosted-environments-configuration#on-demand-runners>), a second process you host, which starts runners as sessions queue; each runner exits on its own when its work finishes. Either way, you set the environment up once, and it appears in the picker on every supported surface. ## @@ -29,7 +29,7 @@ * **Plans** : public beta for Team and Enterprise organizations. Self-hosted environments are off by default; an [Owner](</docs/en/cloud-environments#organization-shared-environments>) turns on **Allow self-hosted environments** on the [**Cloud environments** admin page](<https://claude.ai/admin-settings/cloud-environments>), which requires [Claude Code on the web](</docs/en/claude-code-on-the-web>) to be enabled for the organization. * **Zero Data Retention** : unavailable for organizations with [Zero Data Retention](</docs/en/zero-data-retention>) enabled. * **Model inference** : sessions use the Anthropic API, and inference can’t be routed through [Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry](</docs/en/third-party-integrations>), or an [LLM gateway](</docs/en/llm-gateway>). - * **Surfaces** : sessions started from [Claude Code on the web](</docs/en/claude-code-on-the-web>), the mobile and desktop apps, [scheduled routines](</docs/en/routines>), and the terminal, with [`claude --cloud`](</docs/en/claude-code-on-the-web#from-terminal-to-web>) or an [`--environment` dispatch](</docs/en/self-hosted-environments-testing#run-the-test-loop>), can run in self-hosted environments. [Claude Tag](<https://claude.com/docs/claude-tag/overview>), [Claude Security](</docs/en/claude-security>), and [Code Review](</docs/en/code-review>) sessions don’t route to them yet. Support for those surfaces follows separately. + * **Surfaces** : sessions started from [Claude Code on the web](</docs/en/claude-code-on-the-web>), the mobile and desktop apps, [scheduled routines](</docs/en/routines>), and the terminal, with [`claude --cloud`](</docs/en/claude-code-on-the-web#from-terminal-to-web>) or an [`--environment` dispatch](</docs/en/self-hosted-environments-testing#run-the-test-loop>), can run in self-hosted environments. [Claude Tag](<https://claude.com/docs/claude-tag/overview>) sessions can run in them too, but Claude can’t use [Access bundles](<https://claude.com/docs/claude-tag/concepts/glossary#access-bundle>) in those sessions yet. [Claude Security](</docs/en/claude-security>) and [Code Review](</docs/en/code-review>) sessions don’t route to them yet. Support for those two surfaces follows separately. * **Repositories** : sessions check out repositories from GitHub; see [GitHub authentication options](</docs/en/claude-code-on-the-web#github-authentication-options>). * **Billing** : sessions in a self-hosted environment consume your organization’s Claude Code usage the same way sessions in Anthropic-hosted environments do. @@ -68,7 +68,12 @@ Runner| The long-lived process you deploy. A runner registers with the environment, receives a runner token, and polls for sessions. Session| One Claude Code task, started from claude.ai, the mobile app, or another Anthropic surface such as a scheduled routine or an agent. Each session runs as a child Claude Code process the runner spawns. -In API fields, token claims, and metric names, the environment appears as `pool`, and the environment ID is the `pool_id`. The [reference](</docs/en/self-hosted-environments-reference>) maps the two spellings, including the deprecated `pool` flag names. A runner serves one user at a time. The first session a runner picks up locks the runner to that user, and the runner then runs sessions only for that user, up to a configured capacity. The minimum fleet size is therefore the number of users you expect to be active at once. +In API fields, token claims, and metric names, the environment appears as `pool`, and the environment ID is the `pool_id`. The [reference](</docs/en/self-hosted-environments-reference>) maps the two spellings, including the deprecated `pool` flag names. A runner serves one owner at a time. The first session a runner picks up locks the runner to that session’s owner, and the runner then runs sessions only for that owner, up to a configured capacity. Who the owner is depends on how the session started: + + * **Sessions a user starts** : the owner is that user’s account. + * **Claude Tag channel sessions** : Claude runs them with no user account attached, so the owner is the [Claude Tag agent](<https://claude.com/docs/claude-tag/concepts/glossary#agent-identity>) that started the session. Every channel session that agent starts has the same owner, whoever sent the Slack message, so a runner locked to it serves sessions that different people started when you run it at a `--capacity` above one or with a positive `--drain-grace-sec`. A runner locked to a user never picks these up, and a runner locked to a Claude Tag agent never picks up a user’s sessions. + +The minimum fleet size is therefore the number of owners you expect to be active at once, counting users and Claude Tag agents. ### @@ -91,12 +96,12 @@ Runner lifecycle -The first session a runner picks up locks the runner to the account of the user who started that session, and the runner runs up to `--capacity` concurrent sessions for that account. While the runner has active sessions and hasn’t received a shutdown signal or reached its retire time, the runner keeps claiming the locked account’s queued work. What happens once they finish depends on [`--drain-grace-sec`](</docs/en/self-hosted-environments-reference#runner-cli-flags>): +The first session a runner picks up locks the runner to that session’s owner, and the runner runs up to `--capacity` concurrent sessions for that owner. While the runner has active sessions and hasn’t received a shutdown signal or reached its retire time, the runner keeps claiming the locked owner’s queued work. What happens once they finish depends on [`--drain-grace-sec`](</docs/en/self-hosted-environments-reference#runner-cli-flags>): - * **At the default of`0`**: the runner exits as soon as its active sessions finish, without polling for more, so the orchestrator you deploy it under, such as Kubernetes, can restart it with a fresh disk, ready to serve any account. - * **At a positive value** : the runner keeps polling the locked account’s queue for that many seconds before exiting. + * **At the default of`0`**: the runner exits as soon as its active sessions finish, without polling for more, so the orchestrator you deploy it under, such as Kubernetes, can restart it with a fresh disk, ready to serve any owner. + * **At a positive value** : the runner keeps polling the locked owner’s queue for that many seconds before exiting. -This lifecycle isolates each user’s checked-out code without requiring the runner to delete disk state between users. How your infrastructure stops a runner decides whether you need `--retire-at`. A kill that delivers `SIGTERM` needs no flag: the runner drains as [Shutdown timing](</docs/en/self-hosted-environments-deploy#shutdown-timing>) describes, or keeps serving the sessions it already holds when you set [`--defer-shutdown-max-min`](</docs/en/self-hosted-environments-deploy#defer-the-drain-past-the-first-signal>). If your infrastructure instead destroys hosts at a known wall-clock time without a signal, or with a grace period too short to drain, such as a sandbox lifetime cap or spot-instance reclamation, pass `--retire-at <epoch-seconds>` set to a few minutes before that time. At the retire time: +This lifecycle isolates each owner’s checked-out code without requiring the runner to delete disk state between owners. How your infrastructure stops a runner decides whether you need `--retire-at`. A kill that delivers `SIGTERM` needs no flag: the runner drains as [Shutdown timing](</docs/en/self-hosted-environments-deploy#shutdown-timing>) describes, or keeps serving the sessions it already holds when you set [`--defer-shutdown-max-min`](</docs/en/self-hosted-environments-deploy#defer-the-drain-past-the-first-signal>). If your infrastructure instead destroys hosts at a known wall-clock time without a signal, or with a grace period too short to drain, such as a sandbox lifetime cap or spot-instance reclamation, pass `--retire-at <epoch-seconds>` set to a few minutes before that time. At the retire time: 1. The runner stops taking new work. 2. The runner releases each active session through the same release path the [`--release-idle-session-min`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) flag uses, so the session resumes on a fresh runner when the user sends their next message. When the runner releases each session depends on its state:
modified Customize sessions in self-hosted environments View current →
--- a/self-hosted-environments-configuration.md +++ b/self-hosted-environments-configuration.md @@ -202,7 +202,7 @@ `CLAUDE_RUNNER_ATTEMPT`| How many spawn requests this session has had. `0` for pre-warming requests. `CLAUDE_RUNNER_ORDER_SERVER_TIME`| Server time from the poll response’s HTTP `Date` header. When the hook verifies the work-order JWT’s `exp`, compare against this value instead of the local clock to tolerate skew. Empty when the gateway omitted the header. `CLAUDE_RUNNER_POOL_ID`| The ID of the environment the new runner should join, in `ccpool_...` form -`CLAUDE_RUNNER_ACCOUNT_ID`| Tagged ID of the account that enqueued the session, for per-account routing, quota, or chargeback. Empty when unavailable. +`CLAUDE_RUNNER_ACCOUNT_ID`| Tagged ID of the account that enqueued the session, for per-account routing, quota, or chargeback. Empty when unavailable, and always empty for Claude Tag channel sessions, which no account enqueues. `CLAUDE_RUNNER_ACCOUNT_EMAIL`| Email of the account that enqueued the session. Empty when unavailable. Treat the email as personally identifiable information and don’t log it. `CLAUDE_RUNNER_PRIMARY_REPO_URL`| URL of the session’s first git source, for routing to a runner with that repository pre-warmed. Empty when the session has no git sources. `CLAUDE_RUNNER_PRIMARY_REPO_REVISION`| Revision of the session’s first git source: branch, SHA, or tag. Empty when unspecified. @@ -370,7 +370,7 @@ How each session’s config is assembled -The runner gives each session its own config directory, seeded from an in-memory snapshot of the host’s `~/.claude/` that the runner captures once at startup: `settings.json`, `CLAUDE.md`, hooks, agents, commands, and skills in your runner image apply to every session as the user-level baseline. Because the snapshot is taken at startup, config changes on a running host take effect only after a runner restart. Set `SELF_HOSTED_RUNNER_HOST_CONFIG_DIR` to seed from a different path, or point it at an empty directory to disable seeding. Repository-committed `.claude/settings.json` layers on top as project settings. Sessions also read [`managed-settings.json`](</docs/en/settings#where-settings-live>) from the standard system path in your runner image, but the managed tier uses one source at a time, and [server-managed settings](</docs/en/server-managed-settings>) are checked first: if your organization delivers any server-managed keys, sessions ignore the runner image’s managed file except for its cross-source keys. Claude Code still reads the `env` block and the other [keys it reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>) from that file, such as the sandbox locks, the sandbox binary paths, and `forceRemoteSettingsRefresh`. See [settings precedence](</docs/en/settings#settings-precedence>). When Anthropic’s control plane supplies a session with [Claude Code hooks](</docs/en/hooks>), the runner installs them alongside, not over, your own configuration. Requires Claude Code v2.1.229 or later. +The runner gives each session its own config directory, seeded from an in-memory snapshot of the host’s `~/.claude/` that the runner captures once at startup: `settings.json`, `CLAUDE.md`, hooks, agents, commands, and skills in your runner image apply to every session as the user-level baseline. Because the snapshot is taken at startup, config changes on a running host take effect only after a runner restart. Set `SELF_HOSTED_RUNNER_HOST_CONFIG_DIR` to seed from a different path, or point it at an empty directory to disable seeding. Repository-committed `.claude/settings.json` layers on top as project settings. Sessions also read [`managed-settings.json`](</docs/en/settings#where-settings-live>) from the standard system path in your runner image. Whether its keys apply alongside [server-managed settings](</docs/en/server-managed-settings>) follows [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>): by default, when your organization delivers any server-managed keys, sessions ignore the runner image’s file apart from the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>), such as the `env` block, the sandbox locks, the sandbox binary paths, and `forceRemoteSettingsRefresh`. See [settings precedence](</docs/en/settings#settings-precedence>). When Anthropic’s control plane supplies a session with [Claude Code hooks](</docs/en/hooks>), the runner installs them alongside, not over, your own configuration. Requires Claude Code v2.1.229 or later. * **Where they land** : the runner writes each supplied hook script to a reserved `hooks/.ccr-launcher/` subdirectory of the session’s config directory and registers the scripts in a separate settings file it passes to the session with `--settings`, leaving the seeded `settings.json` and your own scripts at `hooks/<name>` untouched. The runner recreates the reserved subdirectory for each session and doesn’t seed host content at `~/.claude/hooks/.ccr-launcher/` into sessions. * **Who authors them** : the control plane populates the scripts from fixed constants in its own deployment, never from per-session or third-party input.
modified Deploy self-hosted environments to production View current →
Show diff (135 lines)
--- a/self-hosted-environments-deploy.md +++ b/self-hosted-environments-deploy.md @@ -1,6 +1,6 @@ Self-hosted environments are in public beta on Team and Enterprise plans; [Availability and limitations](</docs/en/self-hosted-environments#availability-and-limitations>) covers the enablement path. This page covers running the fleet in production; see the [quickstart](</docs/en/self-hosted-environments-quickstart>) for your first runner and session. -A [self-hosted environment](</docs/en/self-hosted-environments>) runs Claude Code [cloud sessions](</docs/en/claude-code-on-the-web>) on runners you deploy inside your network, and in production those sessions execute model-directed code on behalf of anyone in your organization. This page is for the operator taking a working environment to production. It works through the deployment in order: what to lock down before connecting real systems, the egress the fleet needs, how sessions authenticate to your git host, the deployment recipes themselves, and what to check when sessions misbehave. +A [self-hosted environment](</docs/en/self-hosted-environments>) runs Claude Code [cloud sessions](</docs/en/claude-code-on-the-web>) on runners you deploy inside your network, and in production those sessions execute model-directed code on behalf of everyone who can dispatch a session to the environment. This page is for the operator taking a working environment to production. It works through the deployment in order: what to lock down before connecting real systems, the egress the fleet needs, how sessions authenticate to your git host, the deployment recipes themselves, and what to check when sessions misbehave. ## @@ -8,11 +8,11 @@ Harden your deployment -A self-hosted runner executes arbitrary, model-directed code on your infrastructure on behalf of any member of your Anthropic organization. Work through each item before you connect an environment to production systems: - - * **Ephemeral, per-session containers** : run each runner process in a fresh container or VM that’s destroyed when the process exits, with `--capacity 1` and the default `--drain-grace-sec 0` so each container serves exactly one session. At a higher capacity, or with a positive drain grace, one container serves multiple sessions from the same locked account; see [Runner lifecycle](</docs/en/self-hosted-environments#runner-lifecycle>). Don’t reuse a filesystem between runner restarts, except in the deliberate pre-warmed checkout setup, and never across accounts. +A self-hosted runner executes arbitrary, model-directed code on your infrastructure on behalf of everyone who can dispatch a session to its environment. That’s any member of your Anthropic organization, and anyone who can start a [Claude Tag](<https://claude.com/docs/claude-tag/overview>) channel session in a scope an Owner routed to the environment. Work through each item before you connect an environment to production systems: + + * **Ephemeral, per-session containers** : run each runner process in a fresh container or VM that’s destroyed when the process exits, with `--capacity 1` and the default `--drain-grace-sec 0` so each container serves exactly one session. At a higher capacity, or with a positive drain grace, one container serves multiple sessions from the same [locked owner](</docs/en/self-hosted-environments#key-concepts>); see [Runner lifecycle](</docs/en/self-hosted-environments#runner-lifecycle>). Don’t reuse a filesystem between runner restarts, except in the deliberate pre-warmed checkout setup, and never across owners. * **No broad credentials in the image** : don’t include long-lived SSH keys, cloud-provider credentials, or personal access tokens that grant more than a session needs. Mint credentials used during a session, such as push or API tokens, per session from your [wrapper script](</docs/en/self-hosted-environments-configuration#wrapper-scripts>). For the initial clone, which happens before the wrapper runs, use a [`checkout` lifecycle hook](</docs/en/self-hosted-environments-configuration#checkout>) or `--use-anthropic-git-proxy`; see Configure git. - * **Keep the environment secret off session-running hosts** : the environment secret can register runners and pick up any org member’s queued sessions. On a fixed fleet it lives on every runner host, where any session’s code can read the secret file. Prefer [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>), where the secret stays on the orchestrator host, which never runs user code, and each runner receives a single-use work order that registers exactly one runner. On a fixed fleet, treat the environment-secret file as readable by every session and rotate the secret after any suspected session compromise. + * **Keep the environment secret off session-running hosts** : the environment secret can register runners and pick up any session queued on the environment. On a fixed fleet it lives on every runner host, where any session’s code can read the secret file. Prefer [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>), where the secret stays on the orchestrator host, which never runs user code, and each runner receives a single-use work order that registers exactly one runner. On a fixed fleet, treat the environment-secret file as readable by every session and rotate the secret after any suspected session compromise. * **Default-deny network egress** : restrict runner and session container outbound traffic at your own network boundary on every environment; Default-deny egress covers what to allow and why. * **Least-privilege host IAM** : the compute identity attached to the runner host, such as an instance profile or node service account, should grant only what the runner itself needs. Sessions should obtain their own credentials through your wrapper script rather than inheriting the host’s. * **Block the cloud metadata endpoint from sessions** : keeping sessions off the host identity requires blocking their access to the cloud metadata endpoint, and subnet-level egress policies don’t intercept link-local metadata traffic, so block it in the container itself: @@ -21,7 +21,7 @@ * An explicit deny for `169.254.169.254` in the session container’s network namespace The block applies to your wrapper script and lifecycle hooks too, since they share the container. Authenticate any token exchange with the [session JWT](</docs/en/self-hosted-environments-identity>) against your own token service over allowlisted egress, or use a file-based web identity such as IAM Roles for Service Accounts (IRSA) on Amazon EKS. * **Per-runner filesystem isolation** : each runner process gets its own working directory that no other process on the host can read or write. Make `--hooks-dir`, the wrapper script, and the host’s `~/.claude/` read-only to the session, either built into the image or mounted read-only. - * **Dispatch is organization-wide** : any member of your Anthropic organization can dispatch a session to any of its environments, and there’s no per-environment access control on dispatch. Treat every runner host as reachable for code execution by every org member, and place data or credentials on a runner host only if every org member is allowed to read them. [`--lock-to-account`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) bounds which account’s sessions a given host executes, but dispatch into the environment itself stays organization-wide. To make self-hosted environments the only picker option, an [Owner](</docs/en/cloud-environments#organization-shared-environments>) can hide Anthropic-hosted environments for the whole organization from the [**Cloud environments** page](<https://claude.ai/admin-settings/cloud-environments>). + * **Dispatch has no per-environment access control** : any member of your Anthropic organization can dispatch a session to any of its environments. If an Owner [routes Claude Tag channels to the environment](</docs/en/cloud-environments#organization-shared-environments>), anyone the [Claude Tag access setting](<https://claude.com/docs/claude-tag/admins/restrict-access#restrict-who-can-use-claude>) admits can start channel sessions that run there. By default that’s anyone in the connected Slack workspace, with or without a Claude account. Treat every runner host as reachable for code execution by everyone who can dispatch to it, and place on a runner host only data and credentials that all of those people are allowed to read. [`--lock-to-account`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) bounds which account’s sessions a given host executes, but it doesn’t narrow who can dispatch into the environment. To make self-hosted environments the only picker option, an [Owner](</docs/en/cloud-environments#organization-shared-environments>) can hide Anthropic-hosted environments for the whole organization from the [**Cloud environments** page](<https://claude.ai/admin-settings/cloud-environments>). * **Enforce the repo-settings guard** : choose the guard mode with [`--confine-repo-settings`](</docs/en/self-hosted-environments-reference#runner-cli-flags>). The default `warn` logs a violation and still spawns the session, `enforce` refuses the session, and `off` disables the scan. The runner scans each repository’s committed settings for: * A grant that resolves outside that session’s own workspace: an `additionalDirectories` entry, an `Edit`, `Write`, or `NotebookEdit` rule in `permissions.allow`, or a `sandbox.filesystem.allowWrite` or `allowRead` entry * A non-empty `env` block @@ -148,7 +148,7 @@ RUN git config --system user.name "Claude" && \ git config --system user.email "noreply@anthropic.com" -Without an identity, `git commit` fails with `Please tell me who you are` and sessions can’t make progress. You can use your own bot identity instead; the runner doesn’t override these values. Don’t bake long-lived or broadly-scoped push credentials into a shared runner image: a credential in the image is available to every session the image runs, across every member of your organization. Instead, mint a short-lived, least-scoped token per session from your [wrapper script](</docs/en/self-hosted-environments-configuration#wrapper-scripts>), using the session creator’s identity decoded from the session JWT. Pair it with an ephemeral per-session container, which requires `--capacity 1`, so no credential outlives the session that minted it; see the hardening section. If you must configure push credentials at the image level, for example for a read-only deploy key, scope them as tightly as your git host allows: +Without an identity, `git commit` fails with `Please tell me who you are` and sessions can’t make progress. You can use your own bot identity instead; the runner doesn’t override these values. Don’t bake long-lived or broadly-scoped push credentials into a shared runner image: a credential in the image is available to every session the image runs, whoever started it. Instead, mint a short-lived, least-scoped token per session from your [wrapper script](</docs/en/self-hosted-environments-configuration#wrapper-scripts>), using the session creator’s identity decoded from the session JWT. Pair it with an ephemeral per-session container, which requires `--capacity 1`, so no credential outlives the session that minted it; see the hardening section. If you must configure push credentials at the image level, for example for a read-only deploy key, scope them as tightly as your git host allows: * An SSH deploy key limited to one repository with a `url.<base>.insteadOf` rewrite * A `credential.helper` that returns a minimally-scoped token @@ -192,7 +192,7 @@ Build the runner image -Anthropic doesn’t publish a pre-built runner image. Build your own around the `claude` binary, layering in whatever toolchain your repositories need: language runtimes, compilers, package managers, and [MCP](</docs/en/mcp>) sidecars. The recipes below use `--capacity 4`, so one container serves up to four concurrent sessions from the same locked account. That doesn’t provide the per-session container isolation in the hardening section: before connecting an environment to production systems, either run the recipes at `--capacity 1` with one container per session, or use [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>), which also keep the environment secret off session-running hosts. This Dockerfile is a minimal starting point: +Anthropic doesn’t publish a pre-built runner image. Build your own around the `claude` binary, layering in whatever toolchain your repositories need: language runtimes, compilers, package managers, and [MCP](</docs/en/mcp>) sidecars. The recipes below use `--capacity 4`, so one container serves up to four concurrent sessions from the same locked owner. That doesn’t provide the per-session container isolation in the hardening section: before connecting an environment to production systems, either run the recipes at `--capacity 1` with one container per session, or use [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>), which also keep the environment secret off session-running hosts. This Dockerfile is a minimal starting point: FROM debian:bookworm-slim ARG CLAUDE_CODE_VERSION @@ -213,9 +213,35 @@ ​ +Size CPU and memory for sessions + +Size a runner’s container or host for the sessions it runs rather than for the runner process. The runner itself polls for work, prepares each session’s checkout, runs your [lifecycle hooks](</docs/en/self-hosted-environments-configuration#lifecycle-hooks>), and starts and supervises the session processes. The load comes from the sessions: each one is a Claude Code process plus whatever it starts, such as builds, test suites, package installs, and [MCP servers](</docs/en/mcp>). For one session, start with the following values, stated as Kubernetes requests and limits or your platform’s equivalent, and treat them as a starting point rather than a requirement: + + * **Memory** : a request and a limit of 4 GiB each, which meets the 4 GB minimum in Claude Code’s [system requirements](</docs/en/setup#system-requirements>). Keep the two equal so the scheduler accounts for the container’s full memory. When the container reaches its memory limit, the kernel kills processes inside it, which can end a session mid-task. + * **CPU** : a request of 2 CPUs and a limit of 4 CPUs, so a session can burst above the request during builds. The kernel throttles a container at its CPU limit rather than killing processes in it, so sessions at the limit run slower but keep running. + +In a Kubernetes container spec, set those starting values with the following `resources` block: + + resources: + requests: + cpu: "2" + memory: 4Gi + limits: + cpu: "4" + memory: 4Gi + +Builds and tests are usually the largest and most variable part of a session’s load, so run a representative build of your repository, measure its peak CPU and memory, and raise any starting value that leaves no room for the Claude Code process on top of that peak. The runner uses `--capacity` to cap how many sessions it runs at once. It doesn’t divide CPU or memory between them, so the sessions on a runner share the container’s CPU and memory. To cap one session’s share, apply limits from your [wrapper script](</docs/en/self-hosted-environments-configuration#wrapper-scripts>). What to give one container therefore depends on how many sessions it serves at once: + + * **One session per runner** : give each container one session’s values. Use this sizing at `--capacity 1`, which the hardening section recommends, and for [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>), where you set the values on the workload your [`spawn-runner` hook](</docs/en/self-hosted-environments-configuration#the-spawn-runner-hook>) submits, such as a Kubernetes Job’s pod template. + * **Several sessions per runner** : at a `--capacity` above one, multiply one session’s values by the capacity, because up to that many sessions can run in the container at the same time. The Kubernetes and Docker Compose recipes run `--capacity 4` with no CPU or memory limits, so add limits sized for the capacity you run. + +## + +​ + Kubernetes -The runner serves `GET /healthz` on port 8080 by default, configurable with `--health-port`, so Kubernetes probes work with no extra setup. The endpoint returns `200` whenever the process is alive, so the probes below detect a dead process, not a stuck one; to catch a runner that stopped polling, alert on the `last_poll_age_seconds` series from [`/metrics`](</docs/en/self-hosted-environments-reference#prometheus-metrics>). The Deployment below mounts the environment secret from a Kubernetes Secret, points the liveness and readiness probes at `/healthz`, and sets a 90-second termination grace period. See Shutdown timing for why the grace period matters. +The runner serves `GET /healthz` on port 8080 by default, configurable with `--health-port`, so Kubernetes probes work with no extra setup. The endpoint returns `200` whenever the process is alive, so the probes below detect a dead process, not a stuck one; to catch a runner that stopped polling, alert on the `last_poll_age_seconds` series from [`/metrics`](</docs/en/self-hosted-environments-reference#prometheus-metrics>). The Deployment below mounts the environment secret from a Kubernetes Secret, points the liveness and readiness probes at `/healthz`, and sets a 90-second termination grace period. See Shutdown timing for why the grace period matters. The manifest sets no CPU or memory `resources` on the runner container. Add a block sized for the capacity you run, as Size CPU and memory for sessions describes. apiVersion: apps/v1 kind: Deployment @@ -372,10 +398,15 @@ Reuse a pre-warmed checkout -For large repositories, the clone can dominate session startup. At `--capacity 1` with no [`checkout` hook](</docs/en/self-hosted-environments-configuration#checkout>), the runner keeps one canonical clone per repository at `<base-dir>/<owner>/<repo>` and reuses it across sessions: it fetches the requested ref, detaches `HEAD`, and resets hard to it, which is near-instant when little has changed. To skip the cold clone, bake a clone into your runner image at that path, which gives every fresh container the warm clone without reusing a disk, or point `--base-dir` at a persistent volume paired with [`--lock-to-account`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) so the disk only ever serves one account. What the reuse path does and doesn’t guarantee: +For large repositories, the clone can dominate session startup. At `--capacity 1` with no [`checkout` hook](</docs/en/self-hosted-environments-configuration#checkout>), the runner keeps one canonical clone per repository at `<base-dir>/<repo-owner>/<repo>` and reuses it across sessions: it fetches the requested ref, detaches `HEAD`, and resets hard to it, which is near-instant when little has changed. To skip the cold clone, supply the clone in one of two ways: + + * **Clone in the image** : build the clone into your runner image at that path. Every fresh container then starts with the warm clone without reusing a disk. + * **Clone on a persistent volume** : on runners you pre-lock to one user’s account with [`--lock-to-account`](</docs/en/self-hosted-environments-reference#runner-cli-flags>), point `--base-dir` at a persistent volume, so the disk only ever serves that account. A pre-locked runner never picks up Claude Tag channel sessions, so this option doesn’t apply to runners that serve them. + +What the reuse path does and doesn’t guarantee: * **Any clone shape works** : a full, shallow, or single-branch clone at the path is used as-is. The runner never passes `--depth` when fetching into an existing clone, so a full pre-warm keeps its full history and a shallow one stays shallow. `CLAUDE_RUNNER_FETCH_DEPTH` (`full`, `0`, or a number; default 50) controls only the cold clone the runner makes when no clone exists yet. - * **Tracked changes reset, untracked files persist** : each session starts from a hard reset that wipes the previous session’s tracked modifications, but the runner never runs `git clean`, so untracked files from the locked account’s earlier sessions stay in the tree. + * **Tracked changes reset, untracked files persist** : each session starts from a hard reset that wipes the previous session’s tracked modifications, but the runner never runs `git clean`, so untracked files from the locked owner’s earlier sessions stay in the tree. * **With the git proxy, the reset becomes a checkout** : with `--use-anthropic-git-proxy`, the runner sanitizes the clone’s `.git/` before each session, keeping the object store, refs, and shallow state but deleting the index, so each session pays a full working-tree checkout instead of a near-instant reset; it still never re-clones. Submodule pre-warms aren’t supported under the proxy. * **Long clones need no workaround** : the runner bounds each git operation with a 120-second no-progress watchdog and a 30-minute hard cap, not a flat timeout, so a slow cold clone that keeps reporting progress completes. @@ -397,7 +428,7 @@ Scale the fleet -Your orchestrator decides when to add or remove runners. Because of the [one-user-per-runner lock](</docs/en/self-hosted-environments#runner-lifecycle>), the minimum replica count is the number of users you expect to be active concurrently; `--capacity` controls parallelism within one user’s sessions, not across users. Two scaling approaches are available: +Your orchestrator decides when to add or remove runners. Because of the [one-owner-per-runner lock](</docs/en/self-hosted-environments#runner-lifecycle>), the minimum replica count is the number of users and Claude Tag agents you expect to be active concurrently; `--capacity` controls parallelism within one owner’s sessions, not across owners. Two scaling approaches are available: * **Fixed fleet** : run a static set of runner replicas and scale on the [Prometheus metrics](</docs/en/self-hosted-environments-reference#prometheus-metrics>) each runner serves * **On-demand runners** : run the `claude self-hosted-runner orchestrator` subcommand, which polls Anthropic for sessions that are queued with no runner available and invokes your `spawn-runner` hook to boot one per session. See [On-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>). @@ -456,7 +487,7 @@ Troubleshooting -For guided diagnosis, run the doctor subcommand on the runner host. It starts an interactive Claude Code session with read-only access to the runner’s logs and state; the only change it can make is requeuing a stuck session. Sign in with `claude auth login` on that host first so the session can query your environment, its runners, and its queued sessions. Without that sign-in, for example when the host authenticates with an API key, it’s limited to the local health endpoint, metrics, and the runner’s log, and it reads the log only if you started the runner with `--log-file`. +For guided diagnosis, run the doctor subcommand on the runner host. The doctor subcommand starts an interactive Claude Code session with the runner’s logs and state attached. Sign in with `claude auth login` on that host first so the session can query your environment, its runners, and its queued sessions. Without that sign-in, for example when the host authenticates with an API key, it’s limited to the local health endpoint, metrics, and the runner’s log, and it reads the log only if you started the runner with `--log-file`. claude self-hosted-runner doctor @@ -464,7 +495,7 @@ * **Runner doesn’t appear in the environment** : confirm the host can reach `api.anthropic.com` over HTTPS, the environment secret is current, and the host clock is within five minutes of real time; larger skew causes authentication to fail. The runner logs `[runner:fatal]` with the rejection reason on auth failure. * **Runner exits at startup with`cannot create or write to base directory`**: the runner can’t create or write to `--base-dir`, which defaults to `/workspace`. Fix the directory’s ownership or point `--base-dir` at a writable path, as described in Keep the base directory and capacity identical across runners. If the runner instead logs `[runner:fatal]` saying the base directory check timed out, the directory is on a hung NFS or CSI mount. Check mount health rather than permissions. The runner prints both of these startup failures to stderr before it opens `--log-file`, so look for them in the terminal or your platform’s container logs rather than the log file. Before v2.1.225, the runner didn’t check the base directory at startup, and this misconfiguration failed sessions after pickup instead. - * **Sessions stay queued** : every online runner may be locked to a different account. Check each runner’s `claude_code_self_hosted_runner_locked_account` [metric](</docs/en/self-hosted-environments-reference#prometheus-metrics>) or its `Picked up session` log lines to see which account holds it. Add replicas, or wait for an existing runner to drain and restart. If the environment uses on-demand runners, check the orchestrator instead; see [On-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>). + * **Sessions stay queued** : every online runner may be locked to a different owner. Check each runner’s `claude_code_self_hosted_runner_locked_account` [metric](</docs/en/self-hosted-environments-reference#prometheus-metrics>) or the `locked_account` field of its `[runner:health]` log line to see who holds it. Both show the owner’s email only after the runner has been issued a session token carrying an `act.email` claim, which a Claude Tag agent’s sessions never do. Without the claim, the runner emits no `locked_account` series and logs `locked_account=yes`, which tells you the runner is locked but not to which owner. Add replicas, or wait for an existing runner to drain and restart. If the environment uses on-demand runners, check the orchestrator instead; see [On-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>). * **Sessions fail immediately after pickup** : open the session in claude.ai/code to see the error. The most common causes are missing git credentials in the runner image and build tools that aren’t installed. An unwritable base directory stops the runner at startup instead of failing sessions. See the **Runner exits at startup with`cannot create or write to base directory`** entry in this list. * **Sessions can’t reach the network through an authenticating egress proxy** : when the source you set with `--proxy-authorization-command` or `--proxy-authorization-file` fails, times out after 30 seconds, or yields an empty value, the runner answers that connection `502 Bad Gateway` and logs why. The runner redacts the command’s stderr in that log and never logs the header value. With `--proxy-authorization-command`, run the command yourself on the host to confirm it prints the whole header value on stdout. If the runner instead exits at startup with `could not start the proxy-authorization listener`, it couldn’t open its loopback listener. * **A session’s branch no longer exists on the remote** : for a git source the session only reads from, the runner skips that source and continues on the remaining ones. For the source the session pushes results to, a deleted branch, typically because it was merged and auto-deleted, fails the session with an error naming the repository and branch and asking you to restore the branch and retry. The runner fails the session with the same error when skipping would leave it with no repository at all. Before v2.1.228, such a session started in an empty directory.
modified Verify session identity in self-hosted environments View current →
--- a/self-hosted-environments-identity.md +++ b/self-hosted-environments-identity.md @@ -1,6 +1,6 @@ Self-hosted environments are in public beta on Team and Enterprise plans; an [Owner](</docs/en/cloud-environments#organization-shared-environments>) enables them by turning on **Allow self-hosted environments** on the [**Cloud environments** admin page](<https://claude.ai/admin-settings/cloud-environments>). This page covers session identity verification; see the [quickstart](</docs/en/self-hosted-environments-quickstart>) for setup and [Deploy to production](</docs/en/self-hosted-environments-deploy>) for the fleet recipes. -A [self-hosted environment](</docs/en/self-hosted-environments>) lets [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions run on infrastructure you operate instead of on Anthropic’s. Because the session runs inside your network, Claude can call your internal services directly. Those services need a way to confirm that a request really came from a Claude Code session in your environment, and to identify which user created that session. Every session in a self-hosted environment receives a signed JSON Web Token (JWT) in the `CLAUDE_CODE_SESSION_ACCESS_TOKEN` environment variable. A session presents the token like any bearer credential; for example, a script Claude runs can call your service with `curl -H "Authorization: Bearer $CLAUDE_CODE_SESSION_ACCESS_TOKEN"`. Anthropic signs the token and publishes the verification keys at a public JWKS endpoint. Your services fetch those keys, verify the signature, and read the claims to decide what access to grant. +A [self-hosted environment](</docs/en/self-hosted-environments>) lets [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions run on infrastructure you operate instead of on Anthropic’s. Because the session runs inside your network, Claude can call your internal services directly. Those services need a way to confirm that a request really came from a Claude Code session in your environment, and to identify the user or service identity that created that session. Every session in a self-hosted environment receives a signed JSON Web Token (JWT) in the `CLAUDE_CODE_SESSION_ACCESS_TOKEN` environment variable. A session presents the token like any bearer credential; for example, a script Claude runs can call your service with `curl -H "Authorization: Bearer $CLAUDE_CODE_SESSION_ACCESS_TOKEN"`. Anthropic signs the token and publishes the verification keys at a public JWKS endpoint. Your services fetch those keys, verify the signature, and read the claims to decide what access to grant. ## @@ -18,13 +18,13 @@ A valid token establishes some facts and deliberately not others: - * **Proves** : Anthropic issued the token for a specific session in a specific environment, and how the session was created: by a user in your organization, or with an organization service key + * **Proves** : Anthropic issued the token for a specific session in a specific environment, and how the session was created: by a user in your organization, or by your organization’s service identity, which is how [Claude Tag channel sessions](<https://claude.com/docs/claude-tag/concepts/agent-identity>) start * **Doesn’t prove** : which process on the runner host presents it. The token sits in an environment variable inside the session, so any code Claude runs, and any tool or MCP server the session starts, can read and present it. Two consequences for your services: * Verify the `aud` claim against your environment ID, the `ccpool_...` value shown with your environment on the [**Cloud environments** admin page](<https://claude.ai/admin-settings/cloud-environments>), to reject tokens issued to any other organization’s environment. - * Scope credentials you derive from the token to what a single coding session should be able to do, not to everything the creating user can do. See Scope derived credentials. + * Scope credentials you derive from the token to what a single coding session should be able to do, not to everything the session’s creator can do. See Scope derived credentials. ### @@ -98,7 +98,7 @@ Read the identity -The creating user’s identity is in the `act` claim: `act.sub` is their Anthropic user ID in the prefixed form `user:<id>`, and `act.email`, when the creating surface recorded one, is their email address. Sessions created with an organization service key carry no user identity, so treat a session as user-created only when `act.sub` carries the `user:` prefix, rather than testing whether identity claims are absent. See the claims reference for the full structure and the flat duplicate claims. +The creating user’s identity is in the `act` claim: `act.sub` is their Anthropic user ID in the prefixed form `user:<id>`, and `act.email`, when the creating surface recorded one, is their email address. Sessions your organization’s service identity creates, including Claude Tag channel sessions, carry an `agent:` subject instead, so treat a session as user-created only when `act.sub` carries the `user:` prefix, rather than testing whether identity claims are absent. See the claims reference for the full structure and the flat duplicate claims. The checks map directly onto standard JWT libraries. The examples below implement the full sequence in Node.js with [`jose`](<https://www.npmjs.com/package/jose>), which handles JWKS fetching, caching, and `kid` selection, and in Python with [`PyJWT`](<https://pyjwt.readthedocs.io/>) and its built-in JWKS client. @@ -182,7 +182,7 @@ Verify the token inside the session -[Wrapper scripts](</docs/en/self-hosted-environments-configuration#wrapper-scripts>) run inside the session, before Claude starts. Instead of calling a JWT library, they can run the runner binary’s `self-hosted-runner decode-token` subcommand. The subcommand reads the token from a positional argument, from `CLAUDE_CODE_SESSION_ACCESS_TOKEN`, or from piped stdin, in that order, then strips the prefix, verifies the signature against the JWKS endpoint, checks expiry, and prints the claims as JSON. The subcommand performs the signature and expiry checks only; it doesn’t check `iss`, `aud`, or `ccr:role`. When your wrapper’s auth decision depends on those claims, read them from the printed JSON and compare them explicitly. This command extracts the creator identity, preferring the SSO provider’s subject, then the email address, then the always-present Anthropic user ID: +[Wrapper scripts](</docs/en/self-hosted-environments-configuration#wrapper-scripts>) run inside the session, before Claude starts. Instead of calling a JWT library, they can run the runner binary’s `self-hosted-runner decode-token` subcommand. The subcommand reads the token from a positional argument, from `CLAUDE_CODE_SESSION_ACCESS_TOKEN`, or from piped stdin, in that order, then strips the prefix, verifies the signature against the JWKS endpoint, checks expiry, and prints the claims as JSON. The subcommand performs the signature and expiry checks only; it doesn’t check `iss`, `aud`, or `ccr:role`. When your wrapper’s auth decision depends on those claims, read them from the printed JSON and compare them explicitly. This command extracts the creator identity, preferring the SSO provider’s subject, then the email address, then the creator’s `act.sub` subject, `user:<id>` or `agent:<id>`: "$CLAUDE_RUNNER_CLAUDE_BIN" self-hosted-runner decode-token | jq -re '.act.attested_by.sub // .act.email // .act.sub' @@ -194,7 +194,7 @@ Claims reference -The table below lists the session token claims relevant to verification. Read identity from the `ccr:*` namespace and the `act` chain; the flat `account_email`, `organization_uuid`, and `account_uuid` claims are backward-compatibility duplicates that may be removed. Sessions created with an organization service key omit `act.email`, `ccr:account_id`, `account_email`, and `account_uuid`. The two email claims are optional for user-created sessions too: Anthropic records them at session creation only when the creating request’s credentials carry an email, and a session dispatched from the CLI can lack both, so key identity on `act.sub` or `ccr:account_id` rather than on email. Tokens can also carry additional claims beyond this table; ignore claims you don’t recognize. +The table below lists the session token claims relevant to verification. Read identity from the `ccr:*` namespace and the `act` chain; the flat `account_email`, `organization_uuid`, and `account_uuid` claims are backward-compatibility duplicates that may be removed. Sessions your organization’s service identity creates, including Claude Tag channel sessions, carry an `agent:` subject in `act.sub` and omit `act.email`, `ccr:account_id`, `account_email`, and `account_uuid`. The two email claims are optional for user-created sessions too: Anthropic records them at session creation only when the creating request’s credentials carry an email, and a session dispatched from the CLI can lack both, so key identity on `act.sub` or `ccr:account_id` rather than on email. Tokens can also carry additional claims beyond this table; ignore claims you don’t recognize. Claim| Type| Description ---|---|--- @@ -220,11 +220,11 @@ The `act` chain -The `act` claim records the full delegation path from the user who created the session down to the [environment](</docs/en/self-hosted-environments#key-concepts>) whose secret admitted the runner, and the identity that created that secret. The creating user is the outermost actor, so `act.sub` identifies them directly. +The `act` claim records the full delegation path from the user or service identity that created the session down to the [environment](</docs/en/self-hosted-environments#key-concepts>) whose secret admitted the runner, and the identity that created that secret. The creator is the outermost actor, so `act.sub` identifies them directly. Path| Description ---|--- -`act.sub`| The creating user’s Anthropic user ID, in the form `user:<id>`. +`act.sub`| The creating user’s Anthropic user ID, in the form `user:<id>`, or `agent:<id>` when your organization’s service identity created the session, as it does for Claude Tag channel sessions. `act.email`| The creating user’s email address, when one was recorded at session creation. Don’t require it; key on `act.sub`. `act.attested_by`| The upstream identity provider’s attestation for the creating user, when available. `act.attested_by.sub` is the subject your SSO provider, such as Google or Okta, issued. Prefer this over `act.email` when mapping to identities in your own systems. `act.act`| The runner that spawned the session. `act.act.sub` is `ccr:runner:<runner_id>`. @@ -237,11 +237,11 @@ Scope derived credentials -The session token identifies the creating user, but don’t treat it as equivalent to that user logging in directly. The token sits in an environment variable inside the session, so any code Claude runs, and any tool or MCP server the session starts, can read and present it. Verification is also offline: a token that verifies against the JWKS stays valid until its `exp`, whatever has happened to the session since, and Anthropic doesn’t publish a revocation feed for session tokens. Bound anything you derive from the token accordingly. When your service exchanges the token for internal credentials, issue credentials scoped to what one coding session should reach: - - * **Limit capabilities** : grant read and write access to the resources the session needs for coding tasks, not administrative capabilities the user holds elsewhere. +The session token identifies the user or service identity that created the session, but don’t treat it as equivalent to that creator logging in directly. The token sits in an environment variable inside the session, so any code Claude runs, and any tool or MCP server the session starts, can read and present it. Verification is also offline: a token that verifies against the JWKS stays valid until its `exp`, whatever has happened to the session since, and Anthropic doesn’t publish a revocation feed for session tokens. Bound anything you derive from the token accordingly. When your service exchanges the token for internal credentials, issue credentials scoped to what one coding session should reach: + + * **Limit capabilities** : grant read and write access to the resources the session needs for coding tasks, not administrative capabilities the creator holds elsewhere. * **Limit lifetime** : bound derived credentials to the token’s `exp`, or shorter. - * **Audit as the session** : record the `ccr:session_id` and `jti` alongside the user identity so you can trace actions back to a specific session. + * **Audit as the session** : record the `ccr:session_id` and `jti` alongside the creator identity so you can trace actions back to a specific session. ##
modified Self-hosted environments quickstart View current →
--- a/self-hosted-environments-quickstart.md +++ b/self-hosted-environments-quickstart.md @@ -101,11 +101,11 @@ Send a follow-up message to a running session -Once a session is running on your environment, send it a follow-up from the `claude` CLI on any machine where you’re logged in with `claude auth login`; the command doesn’t need to run from the machine that started the session. The queue-and-exit form posts one message: +Once a session is running on your environment, send it a follow-up from the `claude` CLI on any machine where you’re logged in with `claude auth login`; the command doesn’t need to run from the machine that started the session. The command posts one message: claude -p "your message" --cloud <session-id> -For `<session-id>`, pass the bare `session_...` or `cse_...` ID or the session’s claude.ai/code URL. A successful send prints `Sent to cloud session.` with the session ID and a view link. Accepted ID forms, JSON output, the interactive attach form, the account and policy requirements, and the error reference are on [Send follow-ups from the CLI](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>), since the command works the same against Anthropic-hosted sessions. +For `<session-id>`, pass the bare `session_...` or `cse_...` ID or the session’s claude.ai/code URL. A successful send prints `Sent to cloud session.` with the session ID and a view link. Accepted ID forms, JSON output, the account and policy requirements, and the error reference are on [Send follow-ups from the CLI](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>), since the command works the same against Anthropic-hosted sessions. ##
modified Self-hosted environments reference View current →
--- a/self-hosted-environments-reference.md +++ b/self-hosted-environments-reference.md @@ -14,12 +14,12 @@ ---|---|---|--- `--api-url <url>`| none| `https://api.anthropic.com`| API base URL. Override only for testing. `--base-dir <path>`| `SELF_HOSTED_RUNNER_BASE_DIR`| `/workspace`; none on Windows| Directory for repository checkouts and per-session working directories. The runner needs write access to this path or its parent. The runner creates the directory at startup and exits with `cannot create or write to base directory` when it can’t create or write to it. Before v2.1.225, the runner created the directory when the first session started, so an unusable path failed sessions rather than startup. On Windows, which isn’t a supported runner host, there is no default: the runner exits at startup unless you pass the flag or set the variable. Use the same value on every runner in an environment. See [Keep the base directory and capacity identical across runners](</docs/en/self-hosted-environments-deploy#keep-the-base-directory-and-capacity-identical-across-runners>). -`--capacity <n>`| none| `1`| Maximum concurrent sessions this runner handles. All sessions belong to the same locked account. Use the same value on every runner in an environment; see [Keep the base directory and capacity identical across runners](</docs/en/self-hosted-environments-deploy#keep-the-base-directory-and-capacity-identical-across-runners>). +`--capacity <n>`| none| `1`| Maximum concurrent sessions this runner handles. All sessions belong to the same locked [owner](</docs/en/self-hosted-environments#key-concepts>). Use the same value on every runner in an environment; see [Keep the base directory and capacity identical across runners](</docs/en/self-hosted-environments-deploy#keep-the-base-directory-and-capacity-identical-across-runners>). `--configure-git`| `SELF_HOSTED_RUNNER_CONFIGURE_GIT=1`| off| Write global git identity and enable Anthropic commit signing at startup. See [Configure git](</docs/en/self-hosted-environments-deploy#configure-git>). `--confine-repo-settings <mode>`| `SELF_HOSTED_RUNNER_CONFINE_REPO_SETTINGS`| `warn`| Sets the mode of the guard that flags a session when a repository’s committed settings try to grant write or read access outside that session’s own workspace, set environment variables, or override the operator’s sandbox or hooks posture, such as `sandbox.enabled: false` or `disableAllHooks`. The default `warn` logs the violation and still starts the session, `enforce` refuses the session, and `off` disables the scan. See [Harden your deployment](</docs/en/self-hosted-environments-deploy#harden-your-deployment>). `--debug-token-dir <path>`| `SELF_HOSTED_RUNNER_DEBUG_TOKEN_DIR`| unset| Write live tokens to disk for inspection. Debug only; don’t use in production. `--defer-shutdown-max-min <n>`| `SELF_HOSTED_RUNNER_DEFER_SHUTDOWN_MAX_MS`| `0`| On the first `SIGTERM` or `SIGINT`, keep serving the sessions already attached instead of draining them, then release whatever is still attached N minutes later and exit. Raise your host’s stop timeout before you set this. See [Defer the drain past the first signal](</docs/en/self-hosted-environments-deploy#defer-the-drain-past-the-first-signal>). `0` disables. Requires Claude Code v2.1.238 or later. -`--drain-grace-sec <n>`| `SELF_HOSTED_RUNNER_DRAIN_GRACE_MS`| `0`| Until the runner receives a shutdown signal or reaches its retire time, controls when the runner exits after its active sessions finish: `0` exits immediately without polling for more, and a positive value keeps the runner alive and re-polling the locked account’s queue for that many seconds first, at the cost of the per-session container isolation described in the [hardening section](</docs/en/self-hosted-environments-deploy#harden-your-deployment>). After a first signal you deferred with [`--defer-shutdown-max-min`](</docs/en/self-hosted-environments-deploy#defer-the-drain-past-the-first-signal>), the runner exits as soon as it holds no sessions, whatever you set here. +`--drain-grace-sec <n>`| `SELF_HOSTED_RUNNER_DRAIN_GRACE_MS`| `0`| Until the runner receives a shutdown signal or reaches its retire time, controls when the runner exits after its active sessions finish: `0` exits immediately without polling for more, and a positive value keeps the runner alive and re-polling the locked owner’s queue for that many seconds first, at the cost of the per-session container isolation described in the [hardening section](</docs/en/self-hosted-environments-deploy#harden-your-deployment>). After a first signal you deferred with [`--defer-shutdown-max-min`](</docs/en/self-hosted-environments-deploy#defer-the-drain-past-the-first-signal>), the runner exits as soon as it holds no sessions, whatever you set here. `--drain-wait-sec <n>`| `SELF_HOSTED_RUNNER_DRAIN_WAIT_MS`| `0`| Once the drain starts, which is on `SIGTERM` unless you set [`--defer-shutdown-max-min`](</docs/en/self-hosted-environments-deploy#defer-the-drain-past-the-first-signal>), wait up to N seconds for each session’s in-flight turn and background tasks to finish before terminating the child. During this wait, the runner counts a background task that has just finished as still running until the follow-up turn that reads its result starts, for at most the `SELF_HOSTED_RUNNER_BG_RESULT_GRACE_MS` window. `--environment-secret-file <path>`| `SELF_HOSTED_RUNNER_ENVIRONMENT_SECRET`| required| Path to a file containing the environment secret, or, for runners spawned by the [orchestrator](</docs/en/self-hosted-environments-configuration#on-demand-runners>), the single-use work-order JWT. `SELF_HOSTED_RUNNER_ENVIRONMENT_SECRET` carries the secret value directly, not a file path. The older `--pool-secret-file` flag and `SELF_HOSTED_RUNNER_POOL_SECRET` variable still work and print a deprecation notice to stderr; preview-program runner builds older than 2.1.216 only recognize those older names. `--exec-path <path>`| `SELF_HOSTED_RUNNER_EXEC_PATH`| own binary| Binary or wrapper script to spawn for each session. See [Wrapper scripts](</docs/en/self-hosted-environments-configuration#wrapper-scripts>). @@ -29,7 +29,7 @@ `--health-port <port>`| `SELF_HOSTED_RUNNER_HEALTH_PORT`| `8080`| Port for the `/healthz` and `/metrics` listener. Set `0` to disable. `--hooks-dir <path>`| `SELF_HOSTED_RUNNER_HOOKS_DIR`| unset| Directory of lifecycle hook scripts. See [Lifecycle hooks](</docs/en/self-hosted-environments-configuration#lifecycle-hooks>). `--kill-session-after-min <n>`| `SELF_HOSTED_RUNNER_MAX_LIFETIME_MS`| `0`| Terminate a session child once it has lived N minutes wall-clock, as a safety limit for stuck sessions. A kill that falls mid-turn is deferred until the turn finishes, bounded by a grace window. `0` disables. -`--lock-to-account <id>`| `SELF_HOSTED_RUNNER_LOCK_TO_ACCOUNT`| unset| Pre-lock the runner to a specific account at startup instead of locking on first session. Accepts an email address or `user_...` ID in the environment’s organization. +`--lock-to-account <id>`| `SELF_HOSTED_RUNNER_LOCK_TO_ACCOUNT`| unset| Pre-lock the runner to a specific account at startup instead of locking on first session. Accepts an email address or `user_...` ID in the environment’s organization. A pre-locked runner never picks up Claude Tag channel sessions, which have no account. `--log-file <path>`| `SELF_HOSTED_RUNNER_LOG_FILE`| unset| Mirror runner logs to a file in addition to stdout and stderr, created with `0600` permissions. Required for `self-hosted-runner doctor` to tail logs locally. `--log-level <level>`| none| `info`| `info` or `debug` `--post-session-hook-timeout-sec <n>`| `SELF_HOSTED_RUNNER_POST_SESSION_HOOK_TIMEOUT_MS`| `60`| Budget for the [`post-session` hook](</docs/en/self-hosted-environments-configuration#post-session>) on every session end, including runner shutdown @@ -140,10 +140,10 @@ `claude_code_self_hosted_runner_info{runner_id,version,client_label}`| Always `1`; useful for fleet inventory and version-drift detection `claude_code_self_hosted_runner_capacity`| Configured `--capacity` `claude_code_self_hosted_runner_active_sessions`| Sessions currently running -`claude_code_self_hosted_runner_locked_account{email}`| Present once the runner has locked to a user. The label value is the account email, and the runner always emits it once locked; if your metrics store is broadly readable, drop or hash the label at scrape time, for example with Prometheus `metric_relabel_configs`. +`claude_code_self_hosted_runner_locked_account{email}`| Present once the runner has locked to a user and a session token carrying an `act.email` claim has been issued. The series is absent on a runner locked to a Claude Tag agent, whose session tokens carry no `act.email`. The label value is the account email; if your metrics store is broadly readable, drop or hash the label at scrape time, for example with Prometheus `metric_relabel_configs`. `claude_code_self_hosted_runner_last_poll_age_seconds`| Seconds since the last successful poll. Alert if over 60. `claude_code_self_hosted_runner_poll_errors_total{error_kind}`| Cumulative PollWork failures by kind: `transport`, `timeout`, `5xx`, `429`, or `4xx`. All five series are present from process start; alert on `rate(...[5m]) > 0`. -`claude_code_self_hosted_runner_sessions_started_total{client_platform}`| Session child processes spawned over the runner’s lifetime, one series per session origin such as `web_claude_ai`, `ios`, `android`, `desktop_app`, or `claude_code_cli`, or `unknown` when the server didn’t send one. The Slack values `claude_in_slack` and `claude-in-slack` are reserved: [Claude Tag](<https://claude.com/docs/claude-tag/overview>) sessions can’t route to self-hosted environments yet, so neither value appears until that support ships. Use `sum()` for the fleet total. +`claude_code_self_hosted_runner_sessions_started_total{client_platform}`| Session child processes spawned over the runner’s lifetime, one series per session origin such as `web_claude_ai`, `ios`, `android`, `desktop_app`, or `claude_code_cli`, or `unknown` when the server didn’t send one. Slack sessions carry either `claude_in_slack` or `claude-in-slack` depending on which Slack integration created them, so match both with a regex selector such as `{client_platform=~"claude[-_]in[-_]slack"}`. Use `sum()` for the fleet total. `claude_code_self_hosted_runner_sessions_completed_total{client_platform}`| Sessions that ended cleanly, labeled the same way. Broader than a plain clean exit: see session lifecycle counter semantics for what counts. `claude_code_self_hosted_runner_sessions_failed_total{client_platform}`| Sessions that ended in failure, labeled the same way. Same caveat: see session lifecycle counter semantics. `claude_code_self_hosted_runner_sessions_interrupted_total{client_platform}`| Sessions the runner terminated for an operational reason rather than a session outcome, labeled the same way. See session lifecycle counter semantics.
modified Test self-hosted environments end to end View current →
--- a/self-hosted-environments-testing.md +++ b/self-hosted-environments-testing.md @@ -90,7 +90,7 @@ `--environment` dispatch behavior -In a non-interactive run, with `-p` or a piped prompt, Claude Code creates the session, prints the session ID and a link to it, and exits. From a terminal, `claude --environment <id> "task"` starts an attached interactive cloud session on the environment instead. The flag takes precedence over the [`remote.defaultEnvironmentId`](</docs/en/settings-reference#remote-defaultenvironmentid>) setting. It doesn’t support `--output-format stream-json`, and can’t be combined with flags that resume, attach to, or preconfigure a session, such as `--resume`, `--continue`, `--teleport`, `--session-id`, or `--init-only`. `--cloud` is rejected with a session ID or URL, and in non-interactive runs when it carries a description. A bare `--cloud` is treated as absent. From a terminal, you can pass the task as the `--cloud` description instead of a positional prompt. +Claude Code creates the session, prints the session ID and a link to it, and exits. The flag takes precedence over the [`remote.defaultEnvironmentId`](</docs/en/settings-reference#remote-defaultenvironmentid>) setting. It doesn’t support `--output-format stream-json`, and can’t be combined with flags that resume, attach to, or preconfigure a session, such as `--resume`, `--continue`, `--teleport`, `--session-id`, or `--init-only`. `--cloud` is rejected with a session ID or URL, and in non-interactive runs when it carries a description. A bare `--cloud` is treated as absent. From a terminal, you can pass the task as the `--cloud` description instead of a positional prompt. ##
modified Configure server-managed settings View current →
--- a/server-managed-settings.md +++ b/server-managed-settings.md @@ -27,7 +27,7 @@ **Server-managed settings**| Organizations without MDM, or users on unmanaged devices| Settings that Claude Code fetches from Anthropic’s servers at startup and refreshes hourly during the session **[Endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>)**| 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 don’t reach [cloud sessions](</docs/en/model-config#surface-coverage>) in Anthropic-hosted environments, so organizations using Claude Code on the web should configure server-managed settings as well. Sessions in a [self-hosted environment](</docs/en/self-hosted-environments>) read the managed settings file in the runner image, but only when server-managed settings deliver no keys, per the settings precedence below and its per-key exceptions. +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>) in Anthropic-hosted environments, so organizations using Claude Code on the web should configure server-managed settings as well. Sessions in a [self-hosted environment](</docs/en/self-hosted-environments>) also read the managed settings file in the runner image. The settings precedence below says when that file applies. ## @@ -136,7 +136,7 @@ Settings precedence -Server-managed settings and [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) 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, apart from the [exceptions to managed settings precedence](</docs/en/settings#exceptions-to-managed-settings-precedence>). Within the managed tier, Claude Code uses the first source that delivers at least one policy key, checking server-managed settings first and then endpoint-managed settings; [Precedence within the managed tier](</docs/en/managed-settings#precedence-within-the-managed-tier>) has the full ranking and the carve-out for `wslInheritsWindowsSettings`. Apart from the exception keys covered next, sources don’t merge: if server-managed settings deliver a policy key, other endpoint-managed settings are ignored. If server-managed settings deliver nothing, endpoint-managed settings apply. If the selected source is an MDM policy or managed settings file whose [`policyHelper`](</docs/en/settings-reference#policyhelper>) supplies managed settings, the helper’s output replaces that source as the only managed configuration for the run. Claude Code doesn’t consult a `policyHelper` configured in MDM or file-based settings while server-managed settings deliver a policy key. 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, and the keys that apply only at the next launch, such as `model`, stay in effect until each client relaunches. Run `/status` to see which managed source is active. +Server-managed settings and [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) 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, apart from the [exceptions to managed settings precedence](</docs/en/settings#exceptions-to-managed-settings-precedence>). Within the managed tier, Claude Code by default uses the first source that delivers at least one policy key, checking server-managed settings first and then endpoint-managed settings, apart from the exception keys covered next. [How Claude Code combines managed sources](</docs/en/managed-settings#precedence-within-the-managed-tier>) has the full ranking, the carve-out for the control keys, and the opt-in that applies every source. If the selected source is an MDM policy or managed settings file whose [`policyHelper`](</docs/en/settings-reference#policyhelper>) supplies managed settings, the helper’s output replaces that source as the only managed configuration for the run. Claude Code doesn’t consult a `policyHelper` configured in MDM or file-based settings while server-managed settings deliver a policy key. 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, and the keys that apply only at the next launch, such as `model`, stay in effect until each client relaunches. Run `/status` to see which managed source is active. ### @@ -166,8 +166,9 @@ **Subsequent launches with cached settings:** * Cached settings apply immediately at startup, except for the withheld environment variables described below + * A cached [`modelPricing`](</docs/en/settings-reference#modelpricing>) doesn’t apply until the session’s fetch confirms the payload. Until then, the cost figures developers see in `/usage` and the status line are at list price * Claude Code fetches fresh settings in the background - * Cached settings persist through network failures. The withheld environment variables remain withheld until a fetch succeeds + * Cached settings persist through network failures. Until a fetch succeeds, the withheld environment variables remain withheld and cost figures stay at list price Claude Code withholds several 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/managed-settings#delivery-mechanisms>) deployed through MDM or `managed-settings.json` are unaffected. The withholding requires Claude Code v2.1.198 or later; before v2.1.198, the whole cached `env` block applies at startup. The withheld categories include: @@ -268,15 +269,7 @@ Platform availability -Server-managed settings require a direct connection to `api.anthropic.com`, and delivery requires the session to authenticate with a Team or Enterprise OAuth login, an OAuth token supplied through `CLAUDE_CODE_OAUTH_TOKEN`, or a directly configured API key. Keys returned by an [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) script don’t trigger the settings fetch. Server-managed settings are not available when using third-party model providers: - - * Amazon Bedrock - * Google Cloud’s Agent Platform - * Microsoft Foundry - * [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) - * Custom API endpoints via `ANTHROPIC_BASE_URL` or third-party [LLM gateways](</docs/en/llm-gateway>) - -If you export a `CLAUDE_CODE_USE_*` provider variable or a non-default `ANTHROPIC_BASE_URL` in your shell, Claude Code skips the settings fetch for your sessions. You can’t clear the export with a server-managed `env` block, because the block arrives through the fetch that the export prevents. An [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) `env` block doesn’t restore the fetch either: Claude Code checks eligibility before it applies managed `env` blocks, so the override changes the session’s provider selection but the fetch stays skipped. To restore server-managed delivery, remove the export from your shell, or set the variable to `""` in your user settings `env` block, which applies before the eligibility check. To enforce policy without relying on users to change their shells, deliver the settings through the endpoint-managed channel instead. For Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) deployments, a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) provides the equivalent remote managed-settings delivery: gateway-signed-in clients fetch managed settings from the gateway instead of `api.anthropic.com`. The failure semantics differ at startup: a gateway client that can’t reach the gateway exits with an error instead of falling back to cached settings, while the hourly background refresh is fail-open on both channels. +Server-managed settings require a direct connection to `api.anthropic.com`, and delivery requires the session to authenticate with a Team or Enterprise OAuth login, an OAuth token supplied through `CLAUDE_CODE_OAUTH_TOKEN`, or a directly configured API key. Keys returned by an [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) script don’t trigger the settings fetch. In a [Cowork](<https://claude.com/docs/cowork/overview>) session in the Claude Desktop app, Claude Code doesn’t fetch server-managed settings from the claude.ai admin console, even when the user signs in with a Team or Enterprise account. [Where and when a policy applies](</docs/en/managed-settings#where-and-when-a-policy-applies>) covers which policy reaches Cowork sessions on the user’s machine and remote Cowork sessions. If you export a `CLAUDE_CODE_USE_*` provider variable or a non-default `ANTHROPIC_BASE_URL` in your shell, Claude Code skips the settings fetch for your sessions. You can’t clear the export with a server-managed `env` block, because the block arrives through the fetch that the export prevents. An [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) `env` block doesn’t restore the fetch either: Claude Code checks eligibility before it applies managed `env` blocks, so the override changes the session’s provider selection but the fetch stays skipped. To restore server-managed delivery, remove the export from your shell, or set the variable to `""` in your user settings `env` block, which applies before the eligibility check. To enforce policy without relying on users to change their shells, deliver the settings through the endpoint-managed channel instead. For Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) deployments, a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) provides the equivalent remote managed-settings delivery: gateway-signed-in clients fetch managed settings from the gateway instead of `api.anthropic.com`. The failure semantics differ at startup: a gateway client that can’t reach the gateway exits with an error instead of falling back to cached settings, while the hourly background refresh is fail-open on both channels. ## @@ -296,11 +289,11 @@ Scenario| Behavior ---|--- -User edits the cached settings file| Tampered file applies at startup, and the next server fetch restores the correct settings, except for the keys that apply only at the next launch, such as `model` or a variable added to the `env` block, which stay in effect until relaunch. In Claude Code v2.1.198 or later, the withheld environment variables in the `env` block don’t apply until the server confirms the payload +User edits the cached settings file| Tampered file applies at startup, and the next server fetch restores the correct settings, except for the keys that apply only at the next launch, such as `model` or a variable added to the `env` block, which stay in effect until relaunch. In Claude Code v2.1.198 or later, the withheld environment variables in the `env` block don’t apply until the server confirms the payload. In Claude Code v2.1.242 or later, a cached [`modelPricing`](</docs/en/settings-reference#modelpricing>) doesn’t apply until the server confirms the payload either, so cost figures are at list price until then User deletes the cached settings file| First-launch behavior occurs: Claude Code fetches the settings asynchronously and doesn’t enforce server-managed settings until the fetch completes 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. Without a cache, Claude Code enforces no server-managed settings until the next successful fetch and still applies any [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) on the device. In Claude Code v2.1.198 or later, the withheld environment variables in the cached `env` block don’t apply on fetch failure; the rest of the cache still applies. With `forceRemoteSettingsRefresh: true`, the CLI exits instead of continuing, except for `claude auth` subcommands. Clients signed in through a Claude apps gateway exit at startup without that setting, with the same `claude auth` exemption +API is unavailable| Cached settings apply if available. Without a cache, Claude Code enforces no server-managed settings until the next successful fetch and still applies any [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) on the device. In Claude Code v2.1.198 or later, the withheld environment variables in the cached `env` block don’t apply on fetch failure. In Claude Code v2.1.242 or later, a cached [`modelPricing`](</docs/en/settings-reference#modelpricing>) doesn’t apply on fetch failure either, so cost figures stay at list price until a fetch succeeds. The rest of the cache still applies. With `forceRemoteSettingsRefresh: true`, the CLI exits instead of continuing, except for `claude auth` subcommands. Clients signed in through a Claude apps gateway exit at startup without that setting, with the same `claude auth` exemption 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
modified Claude Code settings View current →
--- a/settings.md +++ b/settings.md @@ -13,11 +13,11 @@ Scope| File| Who it affects| Use it for ---|---|---|--- User| `~/.claude/settings.json`| You, in every project on this machine| Personal preferences: theme, editor mode, default model, your own permission rules -Shared project| `.claude/settings.json`| Everyone who starts Claude Code in the folder that contains it. In a git repository, commit it so teammates get it| Team permissions, hooks, plugins, and the environment variables the project needs +Shared project| `.claude/settings.json`| Everyone working in the folder that contains it. In a git repository, commit it so teammates get it| Team permissions, hooks, plugins, and the environment variables the project needs Project local| `.claude/settings.local.json`| You, in this one project only. Claude Code keeps it out of git when it creates the file; if you create it by hand, add it to `.gitignore` yourself| Personal overrides for one project, and testing before you share Managed| `managed-settings.json` and other [managed sources](</docs/en/managed-settings#delivery-mechanisms>)| Everyone your organization deploys it to; nothing you set overrides it, apart from a few security-sensitive exceptions| Security policy and compliance requirements -In the File column, `~/.claude` is the `.claude` folder in your home directory, and a bare `.claude` is the `.claude` folder inside the project you start Claude Code in. +In the File column, `~/.claude` is the `.claude` folder in your home directory, and a bare `.claude` is the `.claude` folder inside your project. ### @@ -74,12 +74,12 @@ Where Claude Code keeps the local file in a git repository -When Claude asks permission to run a Bash command and you choose “Yes, and don’t ask again”, Claude Code saves that approval as an allow rule in `.claude/settings.local.json`. If you started Claude Code in a subdirectory or a [worktree](</docs/en/worktrees>) of a git repository, it reads and writes that file at the repository root, so the approval applies across the whole repository. The shared `.claude/settings.json` doesn’t move: Claude Code reads it only from the folder you start in, so start at the repository root to pick up a committed file there. Two details follow from the root location: - - * **When the file stays in the starting directory instead** : outside a git repository, when the repository root is your home directory, on Windows, or when the repository root or its `.git` or `.claude` entry isn’t owned by your user. - * **Paths in the file still resolve from where you started** : a permission rule that starts with `/` or a relative sandbox path keeps covering the directory you started Claude Code in, not the repository root. - -Before v2.1.211, Claude Code kept the file in the starting directory. It still reads a file an earlier version left there alongside the root file; where both set the same key, the root’s value applies, and permission rules from both files apply. The Agent SDK’s [`resolveSettings()`](</docs/en/agent-sdk/typescript#resolvesettings>) helper always reads the file from the starting directory. +When Claude asks permission to run a Bash command and you choose “Yes, and don’t ask again”, Claude Code saves that approval as an `allow` rule in `.claude/settings.local.json`. If you start Claude Code in a subdirectory of a git repository, it reads and writes that file at the repository root and applies the approval across the whole repository. In a [worktree](</docs/en/worktrees>), it uses the file at the main checkout’s root. Two rules qualify the root location: + + * **When the file stays with`.claude/settings.json` instead**: outside a git repository, when the repository root is your home directory, on Windows, or when the repository root or its `.git` or `.claude` entry isn’t owned by your user. + * **Paths in the file don’t anchor at the repository root** : a permission rule that starts with `/` or a relative sandbox path [anchors at the session’s primary working directory](</docs/en/permissions#read-and-edit>) instead. + +Before v2.1.211, Claude Code kept the file in the starting directory. It still reads a file an earlier version left there alongside the root file; where both set the same key, the root’s value applies, and permission rules from both files apply. The Agent SDK’s [`resolveSettings()`](</docs/en/agent-sdk/typescript#resolvesettings>) helper always reads the file from the starting directory. Claude Code reads the shared `.claude/settings.json` from the session’s [primary working directory](</docs/en/permissions#working-directories>), so to use a file committed at the repository root, start Claude Code there. After you [move the session with `/cd`](</docs/en/permissions#move-the-session-to-another-directory>), Claude Code reads both project files from the new directory instead, placing the local file by the same rules. Reading them from the directory you moved to requires Claude Code v2.1.246 or later. ### @@ -93,7 +93,7 @@ * MDM or OS-level policies, and `managed-settings.json` files in a system directory * An embedding host such as Claude Desktop, through the SDK `managedSettings` option; see [Control policy from an embedding host](</docs/en/managed-settings#parent-settings-from-embedding-hosts>) -If you’re the administrator, [Set up Claude Code for your organization](</docs/en/admin-setup>) walks through choosing what to enforce, and [Deploy managed settings](</docs/en/managed-settings>) covers delivery and how to confirm a policy is in force. +In a [Cowork](<https://claude.com/docs/cowork/overview>) session that runs on your machine in the Claude Desktop app, Claude Code doesn’t fetch server-managed settings from the claude.ai admin console, and it reads policy deployed to your device unless your organization’s Claude Desktop configuration sets `requireCoworkFullVmSandbox`. [Where and when a policy applies](</docs/en/managed-settings#where-and-when-a-policy-applies>) covers Cowork and cloud sessions. If you’re the administrator, [Set up Claude Code for your organization](</docs/en/admin-setup>) walks through choosing what to enforce, and [Deploy managed settings](</docs/en/managed-settings>) covers delivery and how to confirm a policy is in force. ## @@ -222,7 +222,7 @@ * [`fallbackModel`](</docs/en/settings-reference#fallbackmodel>) is an ordered chain where position carries meaning, so Claude Code takes the whole value from the highest-precedence file that defines it. * [`modelPicker`](</docs/en/settings-reference#modelpicker>) holds one ordered list of rows plus a replace flag, so Claude Code never merges rows from two sources. It takes the whole value from the highest of managed settings, `--settings`, and user settings that defines it, and ignores the key in project and local settings. Requires Claude Code v2.1.242 or later. - * [`availableModels`](</docs/en/settings-reference#availablemodels>): when the [highest-precedence managed source](</docs/en/managed-settings#precedence-within-the-managed-tier>) defines it, Claude Code applies that list as-is and ignores entries you add in user, project, or local settings, unless an app that embeds Claude Code supplies its own model list; see Exceptions to managed settings precedence. Across non-managed scopes Claude Code merges the arrays as usual. + * [`availableModels`](</docs/en/settings-reference#availablemodels>): when the managed settings Claude Code applies define it, Claude Code applies that list as-is and ignores entries you add in user, project, or local settings, unless an app that embeds Claude Code supplies its own model list; see Exceptions to managed settings precedence. Across managed sources the list never merges either; [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) says which source’s list applies. Across non-managed scopes Claude Code merges the arrays as usual. ### @@ -290,7 +290,7 @@ A managed change hasn’t reached you -Managed sources reach a running session on the schedule in the [delivery table](</docs/en/managed-settings#choose-a-delivery-mechanism>), so restart the session first. If `/status` then names a different source than the one your administrator changed, a higher-priority source applies; [Which managed source Claude Code uses](</docs/en/managed-settings#which-managed-source-claude-code-uses>) gives the order. +Managed sources reach a running session on the schedule in the [delivery table](</docs/en/managed-settings#choose-a-delivery-mechanism>), so restart the session first. If `/status` then names a different source than the one your administrator changed, a higher-priority source applies; [How Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) gives the order. #### @@ -323,6 +323,7 @@ Key| Value Claude Code honors| Notes ---|---|--- [`disableClaudeAiConnectors`](</docs/en/settings-reference#disableclaudeaiconnectors>)| `true` from any scope| Honored even when a managed source sets `false` +[`enableArtifact`](</docs/en/settings-reference#enableartifact>)| `false` from any scope, and `disableArtifact: true` from any scope| Honored even when a managed source sets `true`; nothing turns the [Artifact tool](</docs/en/artifacts#disable-artifacts>) back on. Requires Claude Code v2.1.242 or later [`isolatePeerMachines`](</docs/en/settings-reference#isolatepeermachines>)| `true` from any scope| Honored even when a managed source sets `false` [`remoteControlAtStartup`](</docs/en/settings-reference#remotecontrolatstartup>)| `false` from `.claude/settings.json` or `.claude/settings.local.json`| Honored even when a managed source sets `true`; a project or local `true` is ignored [`crossSessionInbound`](</docs/en/settings-reference#crosssessioninbound>)| A stricter value from `.claude/settings.json` or `.claude/settings.local.json`, on the `accept` < `hold` < `refuse` ladder| Honored over managed, `--settings`, and user values; a project or local value that isn’t stricter is ignored @@ -341,7 +342,7 @@ * **Shared project settings** (`.claude/settings.json`): read, because the file is part of the clone. Commit a setting there to apply it in cloud sessions. * **User and project local settings** (`~/.claude/settings.json` and `.claude/settings.local.json`): not read. Both stay on your machine, and the local file isn’t in the clone. - * **Managed settings** : only [server-managed settings](</docs/en/server-managed-settings>) reach a cloud session; a `managed-settings.json` file or MDM profile on your device doesn’t. A [self-hosted environment](</docs/en/self-hosted-environments>) reads the managed settings file in its runner image only when server-managed settings deliver no keys, apart from the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>); see [settings precedence](</docs/en/server-managed-settings#settings-precedence>). + * **Managed settings** : only [server-managed settings](</docs/en/server-managed-settings>) reach a cloud session; a `managed-settings.json` file or MDM profile on your device doesn’t. A [self-hosted environment](</docs/en/self-hosted-environments>) also reads the managed settings file in its runner image. [How Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) says when that file applies. * **`/config`** : on the web, opens the Claude Code section of your claude.ai settings instead of changing a value. To change a setting for a cloud session, set an [environment variable](</docs/en/cloud-environments#set-environment-variables>) on the environment or commit the key to the repository’s `.claude/settings.json`. [What carries over from your setup](</docs/en/cloud-environments#what-carries-over-from-your-setup>) lists the rest: `CLAUDE.md`, skills, MCP servers, plugins, and credentials.
modified Claude Code settings reference View current →
Show diff (470 lines)
--- a/settings-reference.md +++ b/settings-reference.md @@ -13,7 +13,7 @@ `advisorModel`| Pick which model answers when Claude asks the [advisor tool](</docs/en/advisor>)| Model and responses| Any file `agent`| Start every session as a named [subagent](</docs/en/sub-agents>) with its prompt, tools, and model| Agents, sessions, and worktrees| Any file `agentPushNotifEnabled`| Let Claude send a [push notification to your phone](</docs/en/remote-control#mobile-push-notifications>) when it decides to| Remote, desktop, and notifications| Any file -`allowAllClaudeAiMcps`| Load [claude.ai connectors](</docs/en/mcp>) alongside a deployed [`managed-mcp.json`](</docs/en/managed-mcp#exclusive-control-with-managed-mcp-json>)| MCP| Managed +`allowAllClaudeAiMcps`| Load the [claude.ai connectors](</docs/en/mcp>) Claude Code fetches itself alongside a deployed [`managed-mcp.json`](</docs/en/managed-mcp#exclusive-control-with-managed-mcp-json>)| MCP| Managed `allowedChannelPlugins`| Replace the default allowlist of [channel plugins](</docs/en/channels#restrict-which-channel-plugins-can-run>) that can push messages| Plugins and skills| Managed `allowedHttpHookUrls`| Limit which URLs [HTTP hooks](</docs/en/hooks>) can target| Hooks and automation| Any file `allowedMcpServers`| Allowlist which [MCP servers](</docs/en/mcp>) people can use| MCP| Any file @@ -52,12 +52,12 @@ `companyAnnouncements`| Show your organization’s announcements at startup| Interface and terminal| Any file `crossSessionInbound`| Choose whether Claude Code delivers [messages from your other sessions](</docs/en/cross-session-messaging#control-inbound-messages>), shows a notice without delivering them, or refuses them| Agents, sessions, and worktrees| Any file `defaultShell`| Choose whether Bash or PowerShell runs the shell commands you type with the [`!` prefix](</docs/en/interactive-mode#shell-mode-with-prefix>)| Interface and terminal| Any file -`deniedMcpServers`| Block specific [MCP servers](</docs/en/mcp>) in every scope| MCP| Any file +`deniedMcpServers`| Block specific [MCP servers](</docs/en/mcp>) by URL, command, or name| MCP| Any file `dialogExpiry`| Set how long Claude Code waits for [Remote Control](</docs/en/remote-control>) or an SDK host to answer a forwarded dialog before it cancels the dialog| Interface and terminal| User or managed `diffTool`| Choose whether Claude’s proposed file changes open in the [VS Code](</docs/en/vs-code>) or [JetBrains](</docs/en/jetbrains#features>) diff viewer or stay in the terminal| Global config settings| Global config `disableAgentView`| Turn off background agents and [agent view](</docs/en/agent-view>)| Agents, sessions, and worktrees| Any file `disableAllHooks`| Turn off [hooks](</docs/en/hooks>), a custom [status line](</docs/en/statusline>), and a custom [`@` file suggestion](</docs/en/interactive-mode#quick-commands>) command at once| Hooks and automation| Any file -`disableArtifact`| Turn the [Artifact tool](</docs/en/artifacts>) off for everyone; use `enableArtifact` for yourself| Remote, desktop, and notifications| Any file +`disableArtifact`| Deprecated; use `enableArtifact` to turn the [Artifact tool](</docs/en/artifacts>) off| Remote, desktop, and notifications| Any file `disableAutoMode`| Remove [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) from the permission mode cycle| Permission settings| Any file `disableBrowserExternalNavigation`| Limit the [desktop](</docs/en/desktop>) Browser pane to localhost for people and Claude| Tools| Managed `disableBundledSkills`| Turn off the [skills](</docs/en/skills#bundled-skills>) and [workflows](</docs/en/workflows>) included with Claude Code| Plugins and skills| Any file @@ -75,7 +75,7 @@ `effortLevel`| Save the [`/effort` level](</docs/en/model-config#adjust-effort-level>) so future sessions reason more or less deeply| Model and responses| Any file `emojiCompletionEnabled`| Turn off [`:shortcode:` emoji suggestions and replacement](</docs/en/interactive-mode#emoji-shortcodes>) in the prompt input| Interface and terminal| Any file `enableAllProjectMcpServers`| Approve every server in project [`.mcp.json`](</docs/en/mcp#project-server-approvals-and-workspace-trust>) files without a prompt| MCP| Any file -`enableArtifact`| Turn the [Artifact tool](</docs/en/artifacts>) on or off for yourself| Remote, desktop, and notifications| User or managed +`enableArtifact`| Turn the [Artifact tool](</docs/en/artifacts>) off with a `false` in any file; no file can turn it back on| Remote, desktop, and notifications| Any file `enabledMcpjsonServers`| Approve specific servers from a project’s [`.mcp.json`](</docs/en/mcp#project-server-approvals-and-workspace-trust>)| MCP| Any file `enabledPlugins`| Turn individual [plugins](</docs/en/plugins>) on or off per scope| Plugins and skills| Any file `enableWorkflows`| Turn [dynamic workflows](</docs/en/workflows>) on or off against your plan’s default| Hooks and automation| Any file @@ -104,10 +104,12 @@ `isolatePeerMachines`| Ask you before Claude [messages one of your sessions on another machine](</docs/en/cross-session-messaging#require-approval-for-cross-machine-messages>)| Agents, sessions, and worktrees| Any file `keybindingFlavor`| Make `Ctrl+W` [delete back to the previous whitespace](</docs/en/interactive-mode#make-ctrl-w-delete-back-to-whitespace>), as Bash does| Interface and terminal| Any file `language`| Have Claude respond in a language other than English| Model and responses| Any file +`managedSourcesBehavior`| Compose every [managed source](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) you deploy instead of using the highest-priority one alone| Enterprise and managed settings| Managed `minimumVersion`| Keep [auto-updates](</docs/en/setup#pin-a-minimum-version>) from installing anything below a version| Updates and versioning| Any file `model`| Change the [model](</docs/en/model-config#set-a-default-model-for-new-sessions>) Claude Code starts with| Model and responses| Any file `modelOverrides`| [Map model IDs](</docs/en/model-config#override-model-ids-per-version>) to your provider’s IDs, such as Bedrock ARNs| Model and responses| Any file `modelPicker`| Choose which models the [`/model` picker](</docs/en/model-config#available-models>) lists, in your own order and with your own labels| Model and responses| User or managed +`modelPricing`| Report spend at your organization’s contracted rates instead of list price| Model and responses| Managed `otelHeadersHelper`| Generate rotating [OpenTelemetry](</docs/en/monitoring-usage#dynamic-headers>) headers with your own command| Authentication and providers| Any file `outputStyle`| Change Claude’s role, tone, and output format with an [output style](</docs/en/output-styles>)| Model and responses| Any file `parentSettingsBehavior`| Apply or drop restrictions an [SDK or IDE host](</docs/en/managed-settings#let-an-embedding-host-add-policy>) passes when you deploy [managed settings](</docs/en/managed-settings>)| Enterprise and managed settings| Managed @@ -532,6 +534,63 @@ ​ +`modelPricing` + +Report spend at the rates your organization pays instead of list price. Set it when your organization has contracted rates, so the dollar figures developers see match your bill. Claude Code applies the rates in `/usage`, the [status line](</docs/en/statusline>), the Agent SDK’s `total_cost_usd`, the [`--max-budget-usd`](</docs/en/cli-reference>) limit, and the [OpenTelemetry](</docs/en/monitoring-usage>) cost metric and events. You supply the rates: Claude Code doesn’t read them from your contract or the Claude Console. Requires Claude Code v2.1.242 or later. + + * **Scope** : `Managed`. Deploy the key through server-managed settings, an MDM policy, a `managed-settings.json` file, or a [policy helper](</docs/en/managed-settings#compute-the-policy-with-a-helper-program>). Claude Code ignores it in user, project, and local settings, in `--settings`, and on Windows in the user-writable [HKCU registry](</docs/en/managed-settings#where-each-mechanism-stores-the-policy>). With server-managed settings, each session reports costs at list price until that session’s [settings fetch](</docs/en/server-managed-settings#fetch-and-caching-behavior>) has confirmed the setting. A host application that embeds Claude Code and sets [`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`](</docs/en/env-vars>) can supply a table of its own through the SDK [`managedSettings`](</docs/en/agent-sdk/typescript#options>) option, which Claude Code uses only when no managed source sets the key and only in Claude Code v2.1.246 or later. + * **Type** : object with an optional `multiplier` and an optional `overrides` map + * **Default** : unset, so Claude Code reports list price unless a host application supplies a table + +This example sets contracted rates for Sonnet 4.6 and then reduces every figure, the Sonnet row included, by 15%. Set `multiplier` alone for a flat discount, `overrides` alone for per-model rates, or both: + +managed-settings.json + + { + "modelPricing": { + "multiplier": 0.85, + "overrides": { + "claude-sonnet-4-6": { + "input": 2.4, + "output": 12, + "cacheRead": 0.24, + "cacheWrite": 3 + } + } + } + } + +For the steps, including how to confirm the rates are in effect, see [Report spend at your contracted rates](</docs/en/costs#report-spend-at-your-contracted-rates>). + +#### + +​ + +Fields for `modelPricing` + +Field| Type| What it does +---|---|--- +`multiplier`| number greater than 0 and at most 1| Scales every cost Claude Code computes, whether or not an `overrides` row covers it +`overrides`| map of model ID to a rate object with `input`, `output`, `cacheRead`, and `cacheWrite`, each 0 to 10000| The USD-per-million-token rates for that model, all four required. `cacheWrite` covers both five-minute and one-hour cache writes. See Which models a row applies to + +Claude Code uses a row’s rates exactly as you wrote them, without adding the fast-mode surcharge or the [US-only-inference rate](<https://platform.claude.com/docs/en/about-claude/pricing>). If you also set `multiplier`, Claude Code applies it on top of the row’s rates. Claude Code drops a row with a rate it can’t parse, or a `multiplier` it can’t parse, and keeps the rest; see [Fix a broken settings file](</docs/en/settings#fix-a-broken-settings-file>). + +#### + +​ + +Which models a `modelPricing` row applies to + +Claude Code decides which models a row applies to from the row’s key: + + * **A built-in model’s ID** : a key Claude Code itself uses for a built-in model, whether that key is the model’s own ID, such as `claude-sonnet-4-6`, or its Bedrock, Agent Platform, or Foundry ID. Claude Code applies the row to every dated snapshot ID and provider-specific ID of that model. + * **Any other key** : a key that isn’t a built-in model’s ID, such as a gateway model alias. Claude Code applies the row to that one ID only. When a model ID matches one of your keys exactly and also falls under a row keyed by a built-in model’s ID, Claude Code uses the exact match. + * **A Bedrock application inference profile** : once Claude Code has resolved the profile to the model it routes to, through your `modelOverrides` map or the [`bedrock:GetInferenceProfile` lookup](</docs/en/amazon-bedrock#iam-configuration>), Claude Code applies that model’s row to the profile. + +### + +​ + `outputStyle` Select an [output style](</docs/en/output-styles>) by name. An output style is a saved set of instructions that Claude Code adds to the system prompt to change Claude’s role, tone, and output format, such as the built-in Explanatory and Learning styles or one you wrote yourself. Claude Code builds the style into the system prompt once per conversation. An edit to this key takes effect after you run `/clear` or start a new session. @@ -680,11 +739,11 @@ `allowManagedPermissionRulesOnly` -Make managed settings the only source of `allow`, `ask`, and `deny` permission rules. Claude Code then ignores rules in user, project, local, and `--settings` files, ignores `--allowedTools`, hides the always-allow choices in permission prompts, and stops saving new rules. +Make managed settings the only source of `allow`, `ask`, and `deny` permission rules. Claude Code then ignores rules in user, project, local, and `--settings` files, ignores `--allowedTools`, hides the always-allow choices in permission prompts, and stops saving new rules. When [parent settings from an embedding host](</docs/en/managed-settings#let-an-embedding-host-add-policy>) apply, Claude Code treats them as part of the managed tier: it keeps their `deny` and `ask` rules and drops their `allow` rules and `additionalDirectories`. * **Scope** : `Managed` * **Type** : Boolean - * `true`: managed settings are the only source of `allow`, `ask`, and `deny` rules; Claude Code ignores rules from other files and `--allowedTools`, hides always-allow choices, and stops saving new rules + * `true`: managed settings are the only source of `allow`, `ask`, and `deny` rules; Claude Code ignores rules from other files and `--allowedTools`, drops the `allow` rules and `additionalDirectories` of any host-supplied parent settings that apply while keeping their `deny` and `ask` rules, hides always-allow choices, and stops saving new rules * `false`: Claude Code applies permission rules from user, project, local, and `--settings` files in addition to the managed ones * **Default** : unset, so Claude Code applies permission rules from user, project, and local settings and from `--settings`, in addition to the managed ones @@ -1057,7 +1116,7 @@ } } -Boolean keys take the value from the highest-precedence settings file that sets them, so a managed `enabled` or `failIfUnavailable` overrides anything a developer sets. Array keys merge across every settings file, so a developer can append entries; see [Keep developers from widening the policy](</docs/en/sandboxing#keep-developers-from-widening-the-policy>) for the managed-only locks. To require the sandbox for an organization, see [Enforce sandboxing with managed settings](</docs/en/sandboxing#enforce-sandboxing-with-managed-settings>). +Claude Code takes a Boolean key’s value from the highest-precedence settings file that sets it, so a managed `enabled` or `failIfUnavailable` overrides anything a developer sets. It merges array keys across every settings file the session loads, so a developer can append entries; see [Keep developers from widening the policy](</docs/en/sandboxing#keep-developers-from-widening-the-policy>) for the managed-only locks. To require the sandbox for an organization, see [Enforce sandboxing with managed settings](</docs/en/sandboxing#enforce-sandboxing-with-managed-settings>). ### @@ -1157,7 +1216,7 @@ } } -Excluded commands still go through the regular permission flow. Exclusion is a convenience, not a security boundary: prefer `filesystem.allowWrite` when a tool only needs to write somewhere specific. Entries merge across every settings file, and there is no managed-only lock for this list, so keep a managed list narrow. +Excluded commands still go through the regular permission flow. Exclusion is a convenience, not a security boundary: prefer `filesystem.allowWrite` when a tool only needs to write somewhere specific. Claude Code merges entries across every settings file the session loads, and there is no managed-only lock for this list, so keep a managed list narrow. ### @@ -1211,7 +1270,7 @@ } } -Claude Code enforces these lists at the OS sandbox boundary, so they apply to every subprocess a sandboxed command starts, such as `kubectl`, `terraform`, or `npm`, not only to Claude’s file tools. Your [permission rules](</docs/en/sandboxing#permission-rules>) feed the same lists: `Edit` allow and deny rules join `allowWrite` and `denyWrite`, `Read` deny rules join `denyRead`, and `WebFetch(domain:...)` allow and deny rules join the `network` domain lists. Every list merges across settings files. When you edit a list during a session, Claude Code [applies the change to the running session](</docs/en/settings#when-edits-take-effect>). +Claude Code enforces these lists at the OS sandbox boundary, so they apply to every subprocess a sandboxed command starts, such as `kubectl`, `terraform`, or `npm`, not only to Claude’s file tools. Claude Code adds your [permission rules](</docs/en/sandboxing#permission-rules>) to the same lists: `Edit` allow and deny rules to `allowWrite` and `denyWrite`, `Read` deny rules to `denyRead`, and `WebFetch(domain:...)` allow and deny rules to the `network` domain lists. Unless a managed-only lock is set, Claude Code merges every list across the settings files the session loads. `allowManagedReadPathsOnly` limits `allowRead` to entries from managed settings, and `allowManagedDomainsOnly` does the same for allowed domains. [Configure sandboxing](</docs/en/sandboxing#configure-sandboxing>) covers sources you exclude with `--setting-sources`. When you edit a list during a session, Claude Code [applies the change to the running session](</docs/en/settings#when-edits-take-effect>). #### @@ -1256,7 +1315,7 @@ } } -Entries merge across every settings file: user, project, local, and managed paths combine rather than replace each other, and Claude Code adds the paths from your `Edit(...)` allow permission rules. An `allowWrite` entry can’t lift a [protected path](</docs/en/sandboxing#protected-paths>). +Claude Code merges entries across every settings file the session loads: user, project, local, and managed paths combine rather than replace each other, and Claude Code adds the paths from your `Edit(...)` allow permission rules. An `allowWrite` entry can’t lift a [protected path](</docs/en/sandboxing#protected-paths>). ### @@ -1282,7 +1341,7 @@ } } -Entries merge across every settings file, and Claude Code adds the paths from your `Edit(...)` deny permission rules. +Claude Code merges entries across every settings file the session loads, and adds the paths from your `Edit(...)` deny permission rules. ### @@ -1306,7 +1365,7 @@ } } -Entries merge across every settings file, and Claude Code adds the paths from your `Read(...)` deny permission rules. When `filesystem.disabled` is `true`, Claude Code doesn’t enforce these entries. +Claude Code merges entries across every settings file the session loads, and adds the paths from your `Read(...)` deny permission rules. When `filesystem.disabled` is `true`, Claude Code doesn’t enforce these entries. ### @@ -1333,7 +1392,7 @@ } } -Place a `.` entry in project settings: it resolves to the project root there and to `~/.claude` in user settings. Entries merge across every settings file unless `allowManagedReadPathsOnly` is set. +Place a `.` entry in project settings: it resolves to the project root there and to `~/.claude` in user settings. Claude Code merges entries across every settings file the session loads unless `allowManagedReadPathsOnly` is set. ### @@ -1341,12 +1400,12 @@ `sandbox.filesystem.allowManagedReadPathsOnly` -Honor only the `allowRead` entries that come from managed settings, so developers can’t re-open read access to paths your organization blocked. `denyRead` entries still merge from every settings file. +Honor only the `allowRead` entries that come from managed settings, so developers can’t re-open read access to paths your organization blocked. Claude Code still merges `denyRead` entries from every settings file the session loads. * **Scope** : `Managed` * **Type** : Boolean * `true`: Claude Code honors only the `allowRead` entries from managed settings - * `false`: `allowRead` entries merge from every settings file + * `false`: `allowRead` entries merge from every settings file the session loads * **Default** : `false` This blocks reads of the home directory, re-opens `~/work`, and stops developers from re-opening anything else: @@ -1570,7 +1629,7 @@ Declare the credential files and environment variables to [protect from sandboxed commands](</docs/en/sandboxing#protect-credentials>). Each entry names a file `path` or a variable `name` and a `mode`: `deny` hides the credential inside the sandbox, and `mask` shows sandboxed commands a placeholder while the [sandbox proxy](</docs/en/sandboxing#mask-credentials>) substitutes the real value on outbound requests. Claude Code protects only the entries you list; there is no built-in credential deny list. Requires Claude Code v2.1.187 or later. - * **Scope** : `Any file`. `deny` entries merge from every scope, and Claude Code honors `mask` entries, `allowPlaintextInject`, `awsPairs`, and `sigv4` only from user settings, managed settings, and the `--settings` flag. + * **Scope** : `Any file`. Claude Code honors `mask` entries, `allowPlaintextInject`, `awsPairs`, and `sigv4` only from user settings, managed settings, and the `--settings` flag. * **Type** : object with `files`, `envVars`, `allowPlaintextInject`, `awsPairs`, and `sigv4` * **Default** : unset, so no credentials are protected @@ -1630,7 +1689,7 @@ } } -Paths use the same prefixes as the `sandbox.filesystem.*` settings, and Claude Code merges the arrays from every settings scope. `mask` substitution runs only through the sandbox proxy, so set `sandbox.network.tlsTerminate`, or `allowPlaintextInject` for plain-HTTP test networks. `mask` applies to a single file, so list each credential file individually. Claude Code accepts but ignores the `mask` fields on a `deny` entry. [Mask credential files](</docs/en/sandboxing#mask-credential-files>) covers which settings sources are honored and when an entry falls back to `deny`. Requires Claude Code v2.1.187 or later; `mask` entries require v2.1.221 or later. +Paths use the same prefixes as the `sandbox.filesystem.*` settings, and Claude Code merges the arrays from every settings scope the session loads. [Protect credentials](</docs/en/sandboxing#protect-credentials>) covers what still applies from sources you exclude with `--setting-sources`. Requires Claude Code v2.1.187 or later; `mask` entries require v2.1.221 or later. `mask` substitution runs only through the sandbox proxy, so set `sandbox.network.tlsTerminate`, or `allowPlaintextInject` for plain-HTTP test networks. `mask` applies to a single file, so list each credential file individually. Claude Code accepts but ignores the `mask` fields on a `deny` entry. [Mask credential files](</docs/en/sandboxing#mask-credential-files>) covers which settings sources are honored and when an entry falls back to `deny`. #### @@ -1697,7 +1756,7 @@ } } -The `name` must start with a letter or underscore and contain only letters, digits, and underscores. Claude Code merges the arrays from every settings scope, and `deny` takes precedence when the same variable appears with both modes. `mask` substitution runs only through the sandbox proxy, so set `sandbox.network.tlsTerminate`, or `allowPlaintextInject` for plain-HTTP test networks; see [Mask environment variables](</docs/en/sandboxing#mask-environment-variables>). Claude Code accepts but ignores the `mask` fields on a `deny` entry. Requires Claude Code v2.1.187 or later; `mask` entries require v2.1.199 or later. +The `name` must start with a letter or underscore and contain only letters, digits, and underscores. Claude Code merges the arrays from every settings scope the session loads, and applies `deny` when the same variable appears with both modes. [Protect credentials](</docs/en/sandboxing#protect-credentials>) covers what still applies from sources you exclude with `--setting-sources`. Requires Claude Code v2.1.187 or later; `mask` entries require v2.1.199 or later. `mask` substitution runs only through the sandbox proxy, so set `sandbox.network.tlsTerminate`, or `allowPlaintextInject` for plain-HTTP test networks; see [Mask environment variables](</docs/en/sandboxing#mask-environment-variables>). Claude Code accepts but ignores the `mask` fields on a `deny` entry. #### @@ -2002,7 +2061,7 @@ } } -Claude Code merges this list from every settings source even when `allowManagedDomainsOnly` is set, so a developer can always tighten the deny list. For IPv6 literals, see [IPv6 addresses in domain lists](</docs/en/sandboxing#ipv6-addresses-in-domain-lists>). +Claude Code merges this list from every settings source the session loads even when `allowManagedDomainsOnly` is set, so a developer can always tighten the deny list. For IPv6 literals, see [IPv6 addresses in domain lists](</docs/en/sandboxing#ipv6-addresses-in-domain-lists>). ### @@ -2057,7 +2116,7 @@ } } -Denied domains still merge from every source. See [Keep developers from widening the policy](</docs/en/sandboxing#keep-developers-from-widening-the-policy>). +Denied domains still merge from every source the session loads. See [Keep developers from widening the policy](</docs/en/sandboxing#keep-developers-from-widening-the-policy>). ### @@ -2309,6 +2368,7 @@ * From user settings, `--settings`, and managed settings: at startup, and again in the running session when a saved change alters the merged `env`. * From project and local settings: after you trust the workspace, or at startup in `-p` mode, which never shows the trust dialog, and again when a saved change alters the merged `env`. * Variables Claude Code classifies as safe, such as model selection, timeouts and limits, feature toggles, and telemetry settings: at startup from every settings file. + * After you [move the session with `/cd`](</docs/en/permissions#move-the-session-to-another-directory>) on v2.1.246 or later: the new directory’s project and local `env` values, on top of the previous directory’s. #### @@ -2320,6 +2380,7 @@ * Identity variables that Claude Code’s hosting environments own, such as `CLAUDE_CODE_REMOTE` and `CLAUDE_CODE_ACCOUNT_UUID`, are ignored from every file. * [`CLAUDE_CODE_MESSAGING_SOCKET` and `CLAUDE_CODE_MESSAGING_TOKEN`](</docs/en/env-vars#variables>), which Claude Code exports itself, are ignored from every file. Ignoring the socket variable requires Claude Code v2.1.224 or later, and ignoring the token requires v2.1.228 or later. * [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>), which Claude Code reads from the launch environment only, is ignored from every file; requires v2.1.234 or later. + * [`CLAUDE_CODE_RESTRICTED`](</docs/en/env-vars#variables>), which Claude Code reads from the launch environment only, is ignored from every file. ### @@ -4343,8 +4404,8 @@ * **Scope** : `Managed`. Users can’t re-enable connectors that exclusive control suppressed. * **Type** : Boolean * `true`: Claude Code loads the claude.ai connectors alongside a deployed `managed-mcp.json` - * `false`: a deployed `managed-mcp.json` takes exclusive control of MCP servers and suppresses claude.ai connectors - * **Default** : `false`, so a deployed `managed-mcp.json` suppresses claude.ai connectors + * `false`: a deployed `managed-mcp.json` takes exclusive control of MCP servers and suppresses the claude.ai connectors [Claude Code fetches itself](</docs/en/mcp#how-connectors-reach-claude-code>) + * **Default** : `false`, so a deployed `managed-mcp.json` suppresses the claude.ai connectors Claude Code fetches itself managed-settings.json @@ -4352,7 +4413,7 @@ "allowAllClaudeAiMcps": true } -`allowedMcpServers` and `deniedMcpServers` still apply to the connectors this key loads. Connectors delivered to [cloud sessions](</docs/en/claude-code-on-the-web>) stay suppressed. See [Allow claude.ai connectors alongside the managed set](</docs/en/managed-mcp#allow-claude-ai-connectors-alongside-the-managed-set>). +`allowedMcpServers` and `deniedMcpServers` still apply to the connectors this key loads. Connectors delivered to a [cloud session](</docs/en/claude-code-on-the-web>) whose host carries a `managed-mcp.json`, such as a self-hosted runner, stay suppressed. See [Allow claude.ai connectors alongside the managed set](</docs/en/managed-mcp#allow-claude-ai-connectors-alongside-the-managed-set>). ### @@ -4360,7 +4421,7 @@ `allowedMcpServers` -Allowlist the MCP servers people can use. Claude Code blocks any server that doesn’t match an entry, whichever settings file or `.mcp.json` defined it, including servers from `managed-mcp.json`. Built-in servers such as Claude in Chrome, IDE-provided servers, and servers the CLI itself configures are exempt from the allowlist; the denylist still applies to them. +Allowlist the MCP servers people can use. Claude Code blocks any server that doesn’t match an entry wherever it’s defined, including plugin servers, servers passed with `--mcp-config`, and servers from `managed-mcp.json`. Built-in servers such as Claude in Chrome, the `ide` server Claude Code connects to in a running [VS Code](</docs/en/vs-code#the-built-in-ide-mcp-server>) or [JetBrains](</docs/en/jetbrains#the-built-in-ide-mcp-server>) IDE, and servers the CLI itself configures are exempt from the allowlist, and the denylist still applies to them. In-process `type: "sdk"` servers, which the [app that started the session registers](</docs/en/mcp#how-connectors-reach-claude-code>), are exempt from both lists. * **Scope** : `Any file`. Entries from every file merge into one allowlist unless `allowManagedMcpServersOnly` is set. Deploy it in managed settings to enforce it. * **Type** : array of objects, each with exactly one key: `serverName`, a string limited to letters, numbers, hyphens, and underscores; `serverCommand`, an array of the command and its arguments matched exactly; or `serverUrl`, a URL pattern with `*` wildcards @@ -4411,7 +4472,7 @@ `deniedMcpServers` -Block specific MCP servers. Claude Code refuses to load a matching server in every scope, including servers from `managed-mcp.json` and [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>). +Block specific MCP servers. Claude Code refuses to load a matching server wherever it’s defined, including plugin servers, servers passed with `--mcp-config`, servers from `managed-mcp.json`, and the claude.ai connectors [it fetches itself](</docs/en/mcp#how-connectors-reach-claude-code>). In-process `type: "sdk"` servers, which the app that started the session registers, are exempt. * **Scope** : `Any file`. Entries from every file merge into one denylist, and `allowManagedMcpServersOnly` doesn’t change that. Deploy it in managed settings to enforce it. * **Type** : array of objects, each with exactly one key: `serverName`, any non-empty string, so a claude.ai connector’s display name such as `"claude.ai Slack"` works; `serverCommand`, an array of the command and its arguments matched exactly; or `serverUrl`, a URL pattern with `*` wildcards @@ -4433,11 +4494,11 @@ `disableClaudeAiConnectors` -Turn off [claude.ai MCP connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) so Claude Code neither fetches nor connects them. A `true` in any settings file applies: a checked-in project `.claude/settings.json` can opt a repository out of cloud connectors, but a project-level `false` can’t override a user- or managed-level `true`. Requires Claude Code v2.1.182 or later. - - * **Scope** : `Any file` - * **Type** : Boolean - * `true`: Claude Code neither fetches nor connects claude.ai MCP connectors +Turn off the [claude.ai MCP connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) [Claude Code fetches itself](</docs/en/mcp#how-connectors-reach-claude-code>), so it neither fetches nor connects them. A `true` in any settings file applies: a checked-in project `.claude/settings.json` can opt a repository out of those connectors, but a project-level `false` can’t override a user- or managed-level `true`. Requires Claude Code v2.1.182 or later. + + * **Scope** : `Any file` + * **Type** : Boolean + * `true`: Claude Code neither fetches nor connects those connectors * `false`: the same as unset; Claude Code fetches your connectors unless another settings file or `ENABLE_CLAUDEAI_MCP_SERVERS` turns them off * **Default** : `false`, so Claude Code fetches your connectors * **Per-session overrides** : [`ENABLE_CLAUDEAI_MCP_SERVERS`](</docs/en/env-vars>) set to `false` turns connectors off for one session; whichever of the two turns them off, the other can’t turn them back on @@ -4564,7 +4625,7 @@ "crossSessionInbound": "hold" } -Claude Code reads managed settings first, then the `--settings` flag, then user settings, and applies the first value found. `refuse` is stricter than `hold`, and `hold` is stricter than `accept`. When none of the trusted sources sets a value, a project or local `hold` or `refuse` still applies, replacing the per-message default. In sessions with cross-session messaging, this key appears in `/config` as **Messages from your other sessions** , which writes it to user settings; the row requires Claude Code v2.1.232 or later, and Claude Code hides it while the `--settings` flag or managed settings set the key. +Claude Code reads managed settings first, then the `--settings` flag, then user settings, and applies the first value found. `refuse` is stricter than `hold`, and `hold` is stricter than `accept`. When none of the trusted sources sets a value, a project or local `hold` or `refuse` still applies, replacing the per-message default. In sessions with cross-session messaging, this key appears in `/config` as **Messages from your other sessions** , which writes it to user settings; the row requires Claude Code v2.1.232 or later, and Claude Code hides it while the `--settings` flag or managed settings set the key. Claude Code [warns](</docs/en/errors#crosssessioninbound-must-be-one-of-accept-hold-refuse>) when you set a value it doesn’t recognize. While that value is present in a user, project, local, or `--settings` file, Claude Code holds inbound messages, even when a source that takes precedence sets `accept`. A `refuse` that another source sets still applies. Fix or remove the value to clear the hold. When the unrecognized value is in [managed settings](</docs/en/managed-settings>), Claude Code instead treats it as `refuse` until an administrator fixes it. Before v2.1.248, Claude Code ignored an unrecognized value without warning. ### @@ -4833,14 +4894,16 @@ `disableArtifact` -Turn off the [Artifact](</docs/en/artifacts>) tool, which publishes session output as a private web page on claude.ai, for everyone your settings reach, such as an organization through managed settings. To turn the tool off just for yourself, use `enableArtifact` instead, which the **Artifacts** toggle in `/config` writes to your user settings. Don’t put either key in a project’s `.claude/settings.json`: Claude Code ignores `enableArtifact` there, and a `disableArtifact` there is overridden by any higher-precedence file rather than acting as a lock. - - * **Scope** : `Any file` - * **Type** : Boolean - * `true`: Claude Code turns off the Artifact tool for everyone your settings reach - * `false`: the Artifact tool follows `enableArtifact` and your account’s availability - * **Default** : `false` - * **Per-session overrides** : [`CLAUDE_CODE_DISABLE_ARTIFACT`](</docs/en/env-vars>) set to `1` turns the tool off for one session; whichever of the two turns it off, the other can’t turn it back on +Deprecated, and replaced by `enableArtifact`. Claude Code still honors `disableArtifact: true` as equivalent to `enableArtifact: false`, and ignores `disableArtifact: false`. + +Use `enableArtifact` instead to turn off the [Artifact](</docs/en/artifacts>) tool, which publishes session output as a private web page on claude.ai. When you turn the **Artifacts** row off in `/config`, Claude Code writes `enableArtifact` to your user settings and clears this key. + + * **Scope** : `Any file` + * **Type** : Boolean + * `true`: Claude Code turns the Artifact tool off for every session the file applies to, and no other file turns it back on. Before v2.1.242, a higher-precedence file could override a lower file’s `true` rather than the key acting as a lock + * `false`: ignored; to leave the tool on, remove the key + * **Default** : unset, so the tool follows your account’s [availability](</docs/en/artifacts#availability>) + * **Per-session overrides** : [`CLAUDE_CODE_DISABLE_ARTIFACT`](</docs/en/env-vars>) set to `1` turns the tool off for one session settings.json @@ -4848,7 +4911,7 @@ "disableArtifact": true } -A managed `disableArtifact` takes precedence over a user’s `enableArtifact` choice. +[Disable artifacts](</docs/en/artifacts#disable-artifacts>) lists every way to turn the tool off. ### @@ -4874,7 +4937,7 @@ `disableDesktopLocalSessions` -Turn off Code sessions that run on the device in the [desktop app](</docs/en/desktop#local-sessions-on-managed-devices>), for deployments where developers should work on remote machines over SSH. In the Code tab, the **Local** environment stays in the environment dropdown but is grayed out and can’t be selected, with a tooltip saying your organization turned it off; on Windows the WSL entry is grayed out the same way, though whether WSL sessions run on a managed device at all is [governed separately](</docs/en/admin-setup#wsl-sessions-in-claude-code-desktop>). New sessions default to the first [SSH connection](</docs/en/desktop#ssh-sessions>) if one is configured, and the app refuses to start or resume a session on the device, including an SSH connection back to the same machine. SSH sessions to other hosts and cloud sessions are unaffected. The desktop app reads this key; the terminal CLI ignores it. +Turn off Code sessions that run on the device in the [desktop app](</docs/en/desktop#local-sessions-on-managed-devices>), for deployments where developers should work on remote machines over SSH. In the Code tab, the **Local** environment stays in the environment dropdown but is grayed out and can’t be selected, with a tooltip saying your organization turned it off; on Windows the WSL entry is grayed out the same way, though whether WSL sessions run on a managed device at all is [governed separately](</docs/en/admin-setup#wsl-sessions-in-claude-code-desktop>). New sessions default to the first [SSH connection](</docs/en/desktop#ssh-sessions>) if one is configured, and the app refuses to start or resume a session on the device, including an SSH connection back to the same machine. SSH sessions to other hosts and cloud sessions are unaffected. The desktop app reads this key; the terminal CLI ignores it. Requires Claude Desktop v1.37937.0 or later. * **Scope** : `Managed` * **Type** : Boolean; only the JSON Boolean `true` takes effect @@ -4888,7 +4951,7 @@ "disableDesktopLocalSessions": true } -The desktop app ignores any other value, and a value that isn’t a Boolean, such as the string `"true"` or `1`, also logs a warning. Pair it with `sshConfigs` so users land on a working connection, and with `sshHostAllowlist` to limit which hosts they can reach. See [Local sessions on managed devices](</docs/en/desktop#local-sessions-on-managed-devices>). Claude Desktop supplies Code sessions with policy derived from your desktop configuration, for example the egress allowlist, filesystem sandbox, and MCP restrictions in third-party deployments. Claude Code ignores those parent settings whenever an [admin source](</docs/en/managed-settings#which-managed-source-claude-code-uses>) is present: server-managed settings, an MDM or OS-level policy, or a managed settings file. Deploying this key through one of those on a device that had none before, as in third-party deployments, therefore stops the desktop-derived policies from applying. [Let an embedding host add policy](</docs/en/managed-settings#let-an-embedding-host-add-policy>) covers when parent settings can still merge; this holds for any key you deploy that way, not only this one. +The desktop app ignores any other value, and a value that isn’t a Boolean, such as the string `"true"` or `1`, also logs a warning. Pair it with `sshConfigs` so users land on a working connection, and with `sshHostAllowlist` to limit which hosts they can reach. See [Local sessions on managed devices](</docs/en/desktop#local-sessions-on-managed-devices>). Claude Desktop supplies Code sessions with policy derived from your desktop configuration, for example the egress allowlist, filesystem sandbox, and MCP restrictions in third-party deployments. Claude Code ignores those parent settings whenever an [admin source](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) is present: server-managed settings, an MDM or OS-level policy, or a managed settings file. Deploying this key through one of those on a device that had none before, as in third-party deployments, therefore stops the desktop-derived policies from applying. [Let an embedding host add policy](</docs/en/managed-settings#let-an-embedding-host-add-policy>) covers when parent settings can still merge; this holds for any key you deploy that way, not only this one. ### @@ -4916,13 +4979,13 @@ `enableArtifact` -Turn the [Artifact](</docs/en/artifacts>) tool on or off for yourself. When unset, the default follows the feature’s [availability](</docs/en/artifacts#availability>) for your account. The **Artifacts** row in `/config` writes this key, so you don’t usually edit it by hand. To turn artifacts off for everyone from managed settings, use `disableArtifact` instead. Requires Claude Code v2.1.196 or later. - - * **Scope** : `User or managed`. Claude Code ignores the key in project and local settings so that a repository you clone can’t turn the tool on for you. - * **Type** : Boolean - * `true`: Claude Code turns the Artifact tool on for you where it’s available for your account - * `false`: Claude Code turns the Artifact tool off for you - * **Default** : unset, so the tool follows your account’s availability +Turn off the [Artifact](</docs/en/artifacts>) tool, which publishes session output as a private web page on claude.ai. When you turn the **Artifacts** row off in `/config`, Claude Code writes this key to your user settings, so you don’t usually edit it by hand. Requires Claude Code v2.1.196 or later. + + * **Scope** : `Any file`. Every file can turn the tool off, and none can turn it back on. + * **Type** : Boolean + * `false`: Claude Code turns the Artifact tool off for every session the file applies to + * `true`: the same as leaving the key unset, because it never overrides a `false` from another file, from [`CLAUDE_CODE_DISABLE_ARTIFACT`](</docs/en/env-vars>), or from your organization’s [admin setting](</docs/en/artifacts#manage-artifacts-for-your-organization>) + * **Default** : unset, so the tool follows your account’s [availability](</docs/en/artifacts#availability>) settings.json @@ -4930,7 +4993,7 @@ "enableArtifact": false } -A managed `disableArtifact` and your organization’s [admin setting](</docs/en/artifacts#manage-artifacts-for-your-organization>) take precedence over this key. Requires Claude Code v2.1.196 or later. +While a source other than your own user settings keeps the tool turned off, Claude Code hides the **Artifacts** row in `/config`, because turning it on there wouldn’t change anything. [Disable artifacts](</docs/en/artifacts#disable-artifacts>) lists every way to turn the tool off. Before v2.1.242, Claude Code ignored this key in project and local settings, and a file higher in the [precedence stack](</docs/en/settings#settings-precedence>) could turn the tool back on over a lower file’s off. ### @@ -5562,6 +5625,44 @@ ​ +`managedSourcesBehavior` + +Choose whether Claude Code applies only the highest-priority [managed source](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) your organization delivers, or combines every admin source it delivers. By default Claude Code takes the highest-priority source that carries a [policy key](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) and ignores the rest. A policy key is any settings key other than this one and `wslInheritsWindowsSettings`. So once server-managed settings or an MDM policy deliver a policy key, a `managed-settings.json` file contributes only the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>). With `"merge"`, every admin source you deliver contributes its keys to one combined policy. Requires Claude Code v2.1.242 or later. Set `"merge"` only where every source [ranked](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) below your highest one is under an administrator’s control, because Claude Code then adds entries from a lower source, such as `permissions.allow` rules, to the policy. + + * **Scope** : `Managed`. Claude Code reads this key from the highest-priority source that carries either this key or a policy key, and ignores this key in every source ranked lower, so a lower source can’t opt itself into combining with the source above it. Neither the Windows HKCU registry nor [parent settings from an embedding host](</docs/en/managed-settings#let-an-embedding-host-add-policy>) take part in the merge. + * **Type** : string, one of: + * `"first-wins"`: the highest-priority source that carries a policy key supplies the policy, and lower sources contribute only the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>) + * `"merge"`: every admin source you deliver contributes its keys, combined by the rules below + * **Default** : `"first-wins"` + +Deliver the key in the highest-priority source you deploy. A machine that never receives server-managed settings needs the key in its MDM profile too, because Claude Code reads the key from the highest-priority source that carries it or a policy key. A `managed-settings.json` file is the lowest-ranked admin source, so `"merge"` set there has no source below it to combine with. In server-managed settings, the key looks like this: + + { + "managedSourcesBehavior": "merge" + } + +Under `"merge"`, Claude Code combines each key by its kind. This table gives the rule for each kind; the restriction allowlist and highest-source-only rows name every key they cover, and the other rows give examples: + +Kind of key| How Claude Code combines it| Keys +---|---|--- +Lists| Combines entries from every source| `permissions.allow`, `sandbox.network.allowedDomains`, and other list keys +Locks| Applies the strictest value any source sets. When no source sets a strict value, applies a looser value only from the highest source| `allowManagedPermissionRulesOnly`, `permissions.disableBypassPermissionsMode`, and other boolean or enum locks +Restriction allowlists| Takes the list whole from the highest source that sets it, without adding entries from lower sources. When the highest source doesn’t set one, takes it whole from the next source down| `availableModels`, `allowedMcpServers`, `strictKnownMarketplaces`, `allowedChannelPlugins`, and the `fallbackModel` chain +Read from the highest-priority source only| Reads the key only from the highest-priority source that carries a policy key, so a lower source’s value is ignored even when the highest source sets none| `apiKeyHelper`, `awsAuthRefresh`, `awsCredentialExport`, `gcpAuthRefresh`, `otelHeadersHelper`, `proxyAuthHelper`, `forceLoginOrgUUID`, `forceLoginMethod`, `forceLoginGatewayUrl`, `parentSettingsBehavior`, `modelPicker`, `permissions.defaultMode` +`env`| [Merges per variable across admin sources](</docs/en/managed-settings#keys-read-from-every-admin-source>), under both `"first-wins"` and `"merge"`| `env` +Every other key| Takes the value from the highest source that sets it| `cleanupPeriodDays`, `model` + +Two of those keys add a condition of their own: + + * **`modelOverrides`** : pairs with `availableModels`. Claude Code takes `modelOverrides` from the highest source that sets it, unless a higher source sets `availableModels` without `modelOverrides`. In that case it ignores `modelOverrides` from every source. + * **`forceLoginGatewayUrl` and the `"gateway"` value of `forceLoginMethod`**: Claude Code honors them only when the highest source is an MDM policy or a managed settings file, so under server-managed settings neither applies. + +To confirm which sources combined on a machine, run `/status` and [read the `Setting sources` line](</docs/en/managed-settings#read-the-source-in-/status>). + +### + +​ + `parentSettingsBehavior` Choose whether Claude Code applies managed settings supplied by an embedding host process, such as the Agent SDK or an IDE extension, when an admin-deployed managed tier is also present. With `"first-wins"`, Claude Code drops the host-supplied settings; with `"merge"`, it applies them under the admin tier through a restrictive-only filter. Set `"merge"` when a host needs to pass its own restrictions to the sessions it launches, for example Claude Desktop delivering a gateway’s egress allowlist. @@ -5690,11 +5791,11 @@ `wslInheritsWindowsSettings` -Have Claude Code on WSL read managed settings from the Windows policy chain, with HKLM and the Windows managed settings file taking priority over `/etc/claude-code` and HKCU below it. While the chain is on, Claude Code reads `/etc/claude-code` only when no managed settings file or drop-in under `C:\Program Files\ClaudeCode\` delivers a policy key other than `wslInheritsWindowsSettings` itself. Set it to extend the policy you already deploy on Windows to WSL sessions on the same machine, so they follow the same rules as host sessions. Claude Code honors it only when set in the HKLM registry key or in a managed settings file or drop-in under `C:\Program Files\ClaudeCode\`, both of which require Windows admin to write. +Have Claude Code on WSL read managed settings from the Windows policy chain, with HKLM and the Windows managed settings file taking priority over `/etc/claude-code` and HKCU below it. While the chain is on, Claude Code reads `/etc/claude-code` only when no managed settings file or drop-in under `C:\Program Files\ClaudeCode\` delivers a [policy key](</docs/en/managed-settings#how-claude-code-combines-managed-sources>). Set it to extend the policy you already deploy on Windows to WSL sessions on the same machine, so they follow the same rules as host sessions. Claude Code honors it only when set in the HKLM registry key or in a managed settings file or drop-in under `C:\Program Files\ClaudeCode\`, both of which require Windows admin to write. * **Scope** : `Managed`. In an admin-controlled Windows source. * **Type** : Boolean - * `true`: Claude Code on WSL reads managed settings from the Windows policy chain, and reads `/etc/claude-code` only when no managed settings file or drop-in under `C:\Program Files\ClaudeCode\` delivers a policy key other than `wslInheritsWindowsSettings` + * `true`: Claude Code on WSL reads managed settings from the Windows policy chain, and reads `/etc/claude-code` only when no managed settings file or drop-in under `C:\Program Files\ClaudeCode\` delivers a [policy key](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) * `false`: WSL reads only `/etc/claude-code` * **Default** : `false`, so WSL reads only `/etc/claude-code`
modified Customize your status line View current →
--- a/statusline.md +++ b/statusline.md @@ -132,6 +132,7 @@ * Vim mode toggles * You change the `command` in your `statusLine` settings * A `refreshInterval` timer elapses, if you set one + * A rate-limit window in the data your script last received reaches its `resets_at` time Claude Code debounces updates at 300ms, so rapid changes batch together and your script runs once after the changes stop. A change to the `command` itself skips the debounce: Claude Code runs the new command right away. If a new update triggers while your script is still running, Claude Code cancels the in-flight script. If you edit your script, the changes appear the next time an update trigger re-runs it. The event-driven triggers can go quiet when the main session is idle, for example while a coordinator waits on background subagents. To keep time-based or externally-sourced segments current during idle periods, set `refreshInterval` to also re-run the command on a fixed timer. **What your script can output** @@ -159,7 +160,7 @@ `workspace.added_dirs`| Additional directories added via `/add-dir` or `--add-dir`. Empty array if none have been added `workspace.git_worktree`| Git worktree name when the current directory is inside a linked worktree created with `git worktree add`. Absent in the main working tree. Populated for any git worktree, unlike `worktree.*`, which is present only while the session is in a [worktree session](</docs/en/worktrees>) `workspace.repo.host`, `workspace.repo.owner`, `workspace.repo.name`| Repository identity parsed from the `origin` remote, for example `"github.com"`, `"anthropics"`, `"claude-code"`. Absent outside a git repository or when no `origin` remote is configured -`cost.total_cost_usd`| Estimated session cost in USD, computed client-side. May differ from your actual bill. Resets to $0 when `/clear` starts a new session. Before v2.1.211, the total carried over after `/clear` +`cost.total_cost_usd`| Estimated session cost in USD, computed client-side at list price unless a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table is in effect. May differ from your actual bill. Resets to $0 when `/clear` starts a new session. Before v2.1.211, the total carried over after `/clear` `cost.total_duration_ms`| Total wall-clock time since the session started, in milliseconds `cost.total_api_duration_ms`| Total time spent waiting for API responses in milliseconds `cost.total_lines_added`, `cost.total_lines_removed`| Lines of code changed @@ -289,7 +290,7 @@ * `agent`: appears only when running with the `--agent` flag or agent settings configured * `pr`: appears only while an open PR or GitLab merge request is found for the current branch, and is removed once it merges or closes. `pr.review_state` and `pr.kind` may be independently absent * `worktree`: appears only while the session is in a [worktree session](</docs/en/worktrees>). When present, `branch` and `original_branch` may also be absent for hook-based worktrees - * `rate_limits`: appears only for Claude.ai subscribers (Pro/Max) after the first API response in the session. Each window (`five_hour`, `seven_day`) may be independently absent. Use `jq -r '.rate_limits.five_hour.used_percentage // empty'` to handle absence gracefully. + * `rate_limits`: appears only for Claude.ai subscribers (Pro/Max) after the first API response in the session. Each window (`five_hour`, `seven_day`) may be independently absent, and Claude Code drops a window once its `resets_at` time passes. Use `jq -r '.rate_limits.five_hour.used_percentage // empty'` to handle absence gracefully. **Fields that may be`null`**:
modified Streaming Input View current →
--- a/streaming-vs-single-mode.md +++ b/streaming-vs-single-mode.md @@ -16,12 +16,6 @@ Streaming Input Mode (Recommended) Streaming input mode is the **preferred** way to use the Claude Agent SDK. It provides full access to the agent’s capabilities and enables rich, interactive experiences. It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management. - -### - -​ - -How It Works ###
modified Get structured output from agents View current →
--- a/structured-outputs.md +++ b/structured-outputs.md @@ -225,13 +225,6 @@ asyncio.run(main()) -**Benefits:** - - * Full type inference (TypeScript) and type hints (Python) - * Runtime validation with `safeParse()` or `model_validate()` - * Better error messages - * Composable, reusable schemas - ## ​ @@ -372,7 +365,7 @@ `success`| Output was generated and validated successfully `error_max_structured_output_retries`| No valid output remained after multiple attempts (validation failures, or a model-fallback retraction with no successful retry) -A result can also end with subtype `success` but no `structured_output` value, for example when the run completes without the agent producing a structured output. Treat that case as a failure as well. The example below treats a result as successful only when the `subtype` is `success` and `structured_output` is present, and handles every other result as a failure: +A result can also end with subtype `success` but no `structured_output` value, for example when the run completes without the agent producing a structured output. Treat that case as a failure as well. The troubleshooting entry [structured_output is None but the result says success](</docs/en/agent-sdk/troubleshooting#structured_output-is-none-but-the-result-says-success>) covers this case. The example below treats a result as successful only when the `subtype` is `success` and `structured_output` is present, and handles every other result as a failure: TypeScript
modified Create custom subagents View current →
--- 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 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. Those descriptions take up context, so keep them short. When the combined descriptions of your subagents, except the built-in ones, exceed 15,000 tokens, Claude Code shows a [warning at startup with the total token count](</docs/en/errors#agent-descriptions-are-over-the-15000-token-limit>). Trim the `description` fields of your subagents, and move detail into each subagent’s system prompt, which only loads when that subagent runs. ## @@ -116,7 +116,7 @@ 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. In the transcript, the delegation appears as a tool call row showing the subagent’s name followed by a short task description, such as `code-improver (Suggest code improvements)`.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. +Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions. In the transcript, the delegation appears as a tool call row showing the subagent’s name followed by a short task description, such as `code-improver(Suggest code improvements)`.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. @@ -184,7 +184,7 @@ 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-reference#permissions-allow>) in `settings.json` or `settings.local.json`, but these rules apply to the entire session, not only the plugin subagent. -Subagent definitions from any of these scopes are also available to [agent teams](</docs/en/agent-teams#use-subagent-definitions-for-teammates>): when spawning a teammate, you can reference a subagent type and the teammate uses its `tools` and `model`, with the definition’s body appended to the teammate’s system prompt as additional instructions. See [agent teams](</docs/en/agent-teams#use-subagent-definitions-for-teammates>) for which frontmatter fields apply on that path. +Subagent definitions from any of these scopes are also available to [agent teams](</docs/en/agent-teams#use-subagent-definitions-for-teammates>): when spawning a teammate, you can reference a subagent type, and Claude Code applies parts of that definition to the teammate. See [agent teams](</docs/en/agent-teams#use-subagent-definitions-for-teammates>) for which parts apply in each display mode. ### @@ -235,7 +235,7 @@ `disallowedTools`| No| Tools to deny, removed from inherited or specified list `model`| No| Model to use: `sonnet`, `opus`, `haiku`, `fable`, a full model ID (for example, `claude-opus-5`), or `inherit`. Defaults to `inherit` `permissionMode`| No| Permission mode: `default`, `acceptEdits`, `auto`, `dontAsk`, `bypassPermissions`, `plan`, or `manual` as an alias for `default`. The `manual` alias requires Claude Code v2.1.200 or later. Ignored for plugin subagents -`maxTurns`| No| Maximum number of agentic turns before the subagent stops +`maxTurns`| No| Maximum number of agentic turns before the subagent stops. When the subagent reaches the limit, Claude Code returns its output marked as partial, and Claude can resume it to continue. The partial marking requires Claude Code v2.1.246 or later `skills`| No| [Skills](</docs/en/skills>) to preload into the subagent’s context at startup. The full skill content is injected, not only the description. Subagents can still invoke unlisted project, user, and plugin skills through the Skill tool `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 @@ -428,7 +428,7 @@ `default`| Manual mode: prompts for permission `acceptEdits`| Auto-accept file edits and common filesystem commands for paths in the working directory or `additionalDirectories` `auto`| [Auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>): a background classifier reviews commands and protected-directory writes -`dontAsk`| Auto-deny permission prompts. Explicitly allowed tools still work; `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even if you’ve allowed them +`dontAsk`| Auto-deny permission prompts. Explicitly allowed tools still work; `AskUserQuestion`, MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), and connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code are denied even if you’ve allowed them `bypassPermissions`| Skip permission prompts `plan`| Plan mode (read-only exploration) @@ -755,7 +755,7 @@ * **Foreground** : if a rate limit, overload, or server error cuts off a subagent that already produced text output, the Agent tool returns that partial output with a note that the subagent was cut off and didn’t finish its task. A subagent that produced nothing, or whose only output was tool calls, 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. In v2.1.199, a rate limit, overload, or server error that cut off the tool-calls-only shape returned an empty partial result containing only the cut-off note instead. * **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. +When you configure a [fallback model chain](</docs/en/model-config#fallback-model-chains>) and a subagent encounters a failure the chain covers, such as its model being unavailable, Claude Code switches the subagent to the first model in the chain that accepts the request. The subagent keeps working instead of ending on the error. Once the underlying API error clears, ask Claude to retry the task or resume the subagent. ### @@ -802,7 +802,7 @@ When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context. -For tasks that need sustained parallelism or exceed your context window, [agent teams](</docs/en/agent-teams>) give each worker its own independent context. +For work that needs to keep running in parallel or won’t fit in one context window, run it in [separate sessions](</docs/en/agents>) and let Claude [pass findings between them](</docs/en/cross-session-messaging>). #### @@ -902,7 +902,12 @@ Resume subagents -Each subagent invocation creates a new instance rather than continuing an earlier one. 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. Beyond subagents and teammates, in sessions where cross-session messaging is enabled, Claude can use the same tool to message [your other Claude Code sessions](</docs/en/cross-session-messaging>), on this machine or [beyond it](</docs/en/cross-session-messaging#message-sessions-on-other-machines>). To resume a subagent, ask Claude to continue the previous work: +Each subagent invocation creates a new instance rather than continuing an earlier one. 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. + * When a subagent stops at its `maxTurns` limit, Claude Code marks the returned output as partial. For subagents that return an agent ID, Claude Code also notes in the result that Claude can message the subagent to continue from where it stopped. + +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. Beyond subagents and teammates, in sessions where cross-session messaging is enabled, Claude can use the same tool to message [your other Claude Code sessions](</docs/en/cross-session-messaging>), on this machine or [beyond it](</docs/en/cross-session-messaging#message-sessions-on-other-machines>). To resume a subagent, ask Claude to continue the previous work: Use the code-reviewer subagent to review the authentication module [Agent completes] @@ -1013,7 +1018,7 @@ **Best practices:** * **Design focused subagents:** each subagent should excel at one specific task - * **Write detailed descriptions:** Claude uses the description to decide when to delegate + * **Write specific descriptions:** Claude uses the description to decide when to delegate * **Limit tool access:** grant only necessary permissions for security and focus * **Check into version control:** share project subagents with your team
modified Subagents in the SDK View current →
--- a/subagents.md +++ b/subagents.md @@ -156,7 +156,7 @@ `memory`| `'user' | 'project' | 'local'`| No| Memory source for this agent `mcpServers`| `(string | object)[]`| No| MCP servers available to this agent, by name or inline config `initialPrompt`| `string`| No| Auto-submitted as the first user turn when this agent runs as the main thread agent. Ignored when the agent is invoked as a subagent -`maxTurns`| `number`| No| Maximum number of agentic turns before the agent stops +`maxTurns`| `number`| No| Maximum number of agentic turns before the agent stops. When the agent reaches the limit, Claude Code returns its output marked as partial, and you can resume the agent to continue. The partial marking requires Claude Code v2.1.246 or later `background`| `boolean`| No| Run this agent as a non-blocking background task when invoked `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 @@ -396,7 +396,7 @@ 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: +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 stops at its `maxTurns` limit, Claude Code marks the output in the Agent tool result as partial, so Claude knows the run is unfinished. 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
modified Configure your terminal for Claude Code View current →
--- a/terminal-config.md +++ b/terminal-config.md @@ -329,7 +329,7 @@ Paste large content -When you paste more than 800 characters or more than two lines into the prompt, Claude Code collapses the input to a placeholder such as `[Pasted text #1 +120 lines]` so the input box stays usable. The full content is still sent to Claude when you submit. Claude Code keeps the collapsed content under `~/.claude/paste-cache/`, so when you recall a prompt from [command history](</docs/en/interactive-mode#command-history>) and resubmit it, Claude Code sends the full pasted content again, including in a later session, until the retention sweep removes the cache file. Claude Code deletes cache files older than [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>), following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>), so a recalled prompt can reference pasted text that no longer exists. When you submit such a prompt, Claude Code never sends the literal `[Pasted text #N]` string, and shows a notification naming the missing paste: +When you paste more than 800 characters or more than two lines into the prompt, Claude Code collapses the input to a placeholder such as `[Pasted text #1 +120 lines]` so the input box stays usable. The full content is still sent to Claude when you submit. When you delete with a word or line shortcut such as `Ctrl+W` or `Ctrl+K`, or with a vim delete through an `f`/`t` motion such as `df]`, and the deleted range reaches inside a placeholder, Claude Code removes the placeholder whole. You can paste the deletion back to restore it, with [`Ctrl+Y`](</docs/en/interactive-mode#text-editing>) after `Ctrl+W`, `Ctrl+U`, or `Ctrl+K`, or with [`p` in NORMAL mode](</docs/en/interactive-mode#editing-normal-mode>) after a vim delete. Claude Code keeps the collapsed content under `~/.claude/paste-cache/`, so when you recall a prompt from [command history](</docs/en/interactive-mode#command-history>) and resubmit it, Claude Code sends the full pasted content again, including in a later session, until the retention sweep removes the cache file. Claude Code deletes cache files older than [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>), following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>), so a recalled prompt can reference pasted text that no longer exists. When you submit such a prompt, Claude Code never sends the literal `[Pasted text #N]` string, and shows a notification naming the missing paste: * In a plain prompt with text remaining, Claude Code removes the placeholder and sends the remaining text. * In a [shell mode](</docs/en/interactive-mode#shell-mode-with-prefix>) command or a `/` command, where the removal would change what runs, and in any prompt the removal leaves empty, Claude Code cancels the submission and keeps the original text in the input, with the placeholder still in it. Delete the placeholder or edit the command, then resubmit.
modified Tools reference View current →
--- a/tools-reference.md +++ b/tools-reference.md @@ -30,9 +30,9 @@ `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. The [`RemoteTrigger` input reference](</docs/en/agent-sdk/typescript#remotetrigger>) documents every action and the organization policies that remove the tool. Routines live on claude.ai and require a Pro, Max, Team, or Enterprise plan, so this tool is not accessible from Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry. Also unavailable when you turn off [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>)| 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. To end the loop instead, Claude calls it with `stop: true`, which cancels the pending wakeup. The `stop` field requires Claude Code v2.1.202 or later. The pending wakeup appears in `session_crons` in [Stop hook input](</docs/en/hooks#stop-input>). Not available on Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry, where a `/loop` prompt with no interval runs on a fixed schedule instead. The same happens when you turn off [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>)| 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. To end the loop instead, Claude calls it with `stop: true`, which cancels the pending wakeup. The `stop` field requires Claude Code v2.1.202 or later. The pending wakeup appears in `session_crons` in [Stop hook input](</docs/en/hooks#stop-input>)| No `SendFeedback`| Drafts a feedback report about Claude Code, covering a product problem or Claude’s own behavior in the session, and queues it on your machine for you to review. Claude Code sends nothing until you choose to send the draft. See SendFeedback tool behavior. Requires Claude Code v2.1.238 or later| No -`SendMessage`| Sends a message to another agent: an [agent team](</docs/en/agent-teams>) teammate, a [subagent it resumes](</docs/en/sub-agents#resume-subagents>) by agent ID or name, or one of your other Claude Code sessions, on this machine or beyond it. Messaging other sessions requires Claude Code v2.1.224 or later; [cross-session messaging](</docs/en/cross-session-messaging>) covers which sessions Claude can reach and each case’s requirements. A receiver never treats a message from another agent as your consent or approval. Claude can include an optional `summary` input, typically 5-10 words, that Claude Code shows as a one-line preview. When Claude omits it on a [plain-text message](</docs/en/cross-session-messaging#limitations>), Claude Code uses the first line of the message as the summary. Claude Code truncates a summary longer than 200 characters with an ellipsis. With the `notify_when_idle` input, Claude can ask one of your other sessions on this machine to [send one notice when it next goes idle or exits](</docs/en/cross-session-messaging#get-a-notice-when-another-session-goes-idle>). Requires Claude Code v2.1.236 or later in both sessions| No +`SendMessage`| Sends a message to another agent: an [agent team](</docs/en/agent-teams>) teammate, a [subagent it resumes](</docs/en/sub-agents#resume-subagents>) by agent ID or name, or one of your other Claude Code sessions, on this machine or beyond it. Messaging other sessions requires Claude Code v2.1.224 or later. [Cross-session messaging](</docs/en/cross-session-messaging>) covers which sessions Claude can reach, [what a message looks like when it arrives](</docs/en/cross-session-messaging#what-a-message-looks-like>), and [how Claude gets a notice when another session goes idle](</docs/en/cross-session-messaging#get-a-notice-when-another-session-goes-idle>). Claude can include an optional `summary` input, typically 5-10 words, that Claude Code shows as a one-line preview. When Claude omits it on a [plain-text message](</docs/en/cross-session-messaging#limitations>), Claude Code uses the first line of the message as the summary. Claude Code truncates a summary longer than 200 characters with an ellipsis| 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 Cloud’s Agent Platform, 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 @@ -86,7 +86,7 @@ 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 doesn’t see the subagent’s intermediate tool calls or outputs, only that final result. With [agent teams](</docs/en/agent-teams>) enabled, a call that carries a `name` can launch a [teammate](</docs/en/agent-teams#how-claude-starts-agent-teams>) instead, which reports back through team messages rather than by returning a 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>) wherever [fork mode](</docs/en/sub-agents#turn-fork-mode-on-or-off>) is on. A fork inherits the full parent conversation instead of starting fresh, runs in the background apart from the [cases that stay in the foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>), and still surfaces permission prompts in your terminal. The rest of this section describes non-fork subagents. Which tools a non-fork 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. With [agent teams](</docs/en/agent-teams>) enabled, a call that carries a `name` can launch a [teammate](</docs/en/agent-teams#how-claude-starts-agent-teams>) instead, which reports back through team messages rather than by returning a result. To cap how many turns a subagent runs, set `maxTurns` in the [subagent definition](</docs/en/sub-agents#supported-frontmatter-fields>). When the subagent reaches the limit, Claude Code marks the returned result as partial output, and Claude can [resume the subagent](</docs/en/sub-agents#resume-subagents>) to continue. The same Agent tool also launches [forked subagents](</docs/en/sub-agents#fork-the-current-conversation>) wherever [fork mode](</docs/en/sub-agents#turn-fork-mode-on-or-off>) is on. A fork inherits the full parent conversation instead of starting fresh, runs in the background apart from the [cases that stay in the foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>), and still surfaces permission prompts in your terminal. The rest of this section describes non-fork subagents. Which tools a non-fork 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 subagents](</docs/en/sub-agents#available-tools>). * **`tools` only**: the subagent gets only the listed tools. @@ -187,13 +187,29 @@ Memory limit on Linux and WSL -On Linux and WSL, set [`CLAUDE_CODE_TOOL_MEMORY_LIMIT`](</docs/en/env-vars#variables>) to a size such as `4G` to cap the memory that Bash and PowerShell tool commands can use, so one runaway build can’t take the memory the rest of the session needs. Requires Claude Code v2.1.233 or later. +On Linux and WSL, set [`CLAUDE_CODE_TOOL_MEMORY_LIMIT`](</docs/en/env-vars#variables>) to a size such as `4G` to cap the memory that Bash, PowerShell, and Monitor tool commands can use, so one runaway build can’t take the memory the rest of the session needs. Requires Claude Code v2.1.233 or later. Before v2.1.246, Monitor tool commands ran outside the cap. * Write the size as a number of bytes or with a `K`, `M`, `G`, or `T` suffix. Set `0`, `off`, `false`, `no`, or `none` to turn the cap off. Claude Code ignores any other value it can’t read as a size, such as `4e9`. - * Claude Code counts all of a session’s Bash and PowerShell commands against the one cap, not each command on its own. + * Claude Code counts all of a session’s Bash, PowerShell, and Monitor commands against the one cap, not each command on its own. * Claude Code applies the cap with a memory cgroup. When it can’t set the cgroup up, commands run without a cap, and the debug log from `claude --debug` says why. - * After a Bash or PowerShell tool command has turned the cap on, or has turned it off because of an off value or a failed cgroup setup, Claude Code holds that result until you relaunch. To apply a changed or removed value, or a fixed setup, launch `claude` again. + * After the first process Claude Code starts has turned the cap on, or has turned it off because of an off value or a failed cgroup setup, Claude Code holds that result until you relaunch. To apply a changed or removed value, or a fixed setup, launch `claude` again. * When commands can’t stay under the cap, the kernel kills a command, and nothing in its result names the cap. + +Claude Code can also count other kinds of processes it starts against the same limit. Set [`CLAUDE_CODE_TOOL_MEMORY_CGROUP_EXCLUDE`](</docs/en/env-vars#variables>) to a comma-separated list of the kinds to exempt from the cap; Claude Code applies the cap to every kind not on your list. Set it to `none` to cap every kind, or to `all-new` to cap only Bash, PowerShell, and Monitor tool commands. Requires Claude Code v2.1.246 or later. The kinds you can name: + + * `mcp`: local [MCP servers](</docs/en/mcp>) + * `lsp`: language servers + * `hooks`: [hook](</docs/en/hooks>) commands + * `plugin`: commands that [plugins](</docs/en/plugins>) run + * `helper`: Claude Code’s own helper commands, such as `git` + * `agent`: child Claude Code processes, such as [agent teammates](</docs/en/agent-teams>) + +Whatever you list, these rules apply: + + * **Unknown names** : Claude Code ignores names it doesn’t recognize + * **Bash, PowerShell, and Monitor** : Claude Code keeps Bash, PowerShell, and Monitor tool commands under the cap whatever you list + * **Variable unset** : Claude Code takes the set of other capped kinds from configuration Anthropic delivers from the server, and that set can change over time, so set the variable when you need a set that doesn’t change + * **Permission-gating hooks** : even with every kind capped, Claude Code excludes from the cap a hook that can block or change the outcome of an action, and any MCP server that such a hook calls, so the kernel killing a permission-gating hook can’t allow the action it was blocking ##
modified Troubleshooting View current →
--- a/troubleshooting.md +++ b/troubleshooting.md @@ -22,6 +22,11 @@ * If you set `cli_path`, confirm the file exists and is the `claude` executable. * If you rely on `PATH` resolution, confirm `claude --version` works in the same environment your application runs in. Processes you launch outside your shell, such as from an IDE or a service manager, often run with a different `PATH`. +The TypeScript SDK looks for the CLI in its bundled platform package and the path you set in `pathToClaudeCodeExecutable`. Match the message you see: + + * `Native CLI binary for <platform>-<arch> not found`: the bundled platform package is missing, most often because the install skipped optional dependencies. Reinstall `@anthropic-ai/claude-agent-sdk` without skipping optional dependencies, or point `pathToClaudeCodeExecutable` at a [native install](</docs/en/setup#install-claude-code>). In a single-file executable built with `bun build --compile`, the same message has a different cause and fix. See [Compile to a single executable](</docs/en/agent-sdk/typescript#compile-to-a-single-executable>). + * `Claude Code native binary not found at <path>` or `Claude Code executable not found at <path>. Is options.pathToClaudeCodeExecutable set?`: the file at the resolved path is missing, or the process can’t access it. Confirm the file exists at that path and that the process can access it. + ### ​ @@ -45,6 +50,84 @@ Before `claude-agent-sdk` 0.2.124, the Python SDK spawned batch scripts through `cmd.exe` without this check. +### + +​ + +CLIConnectionError: Failed to start Claude Code + +The SDK found a file at the resolved path but couldn’t launch it. Python raises these failures as a `CLIConnectionError`. TypeScript rejects the message iteration with an error carrying no SDK class. The table below maps each message to what it tells you. Match the message you see: + +Message| SDK| What it tells you +---|---|--- +`Failed to start Claude Code: <detail>`| Python| The rest of the message is the operating system’s own error +`Claude Code executable at <path> exists but failed to launch`| TypeScript| The script at the configured path can’t run +`Claude Code native binary at <path> exists but failed to launch`| TypeScript| The binary can’t run, with a libc suggestion appended to the message +`Failed to spawn Claude Code process: <detail>`| TypeScript| Any other launch failure + +In both SDKs, the usual cause is a resolved path that points at something that can’t run, such as a text file, a directory, or a file without execute permission. Read the native-binary message’s libc suggestion as one possible cause. To fix it in either SDK: + + * Confirm the configured path points at the `claude` executable itself and that the file has execute permission. + * If you don’t need a custom path, remove `cli_path` in Python or `pathToClaudeCodeExecutable` in TypeScript so the SDK finds a CLI on its own, preferring its bundled copy. + * When the failing binary is the SDK’s bundled copy in a container image, reinstall the SDK during the image build so the bundled binary matches the container’s platform, or rebuild the image for the architecture it runs on. The usual cause is a binary that doesn’t match the container’s architecture or libc, or one that lost its execute permission in the image build. + +### + +​ + +CLIConnectionError: Not connected + +Calling a `ClaudeSDKClient` method in Python before the client has connected, or after it has disconnected, raises a `CLIConnectionError` with this message: + + Not connected. Call connect() first. + +Do what the message says. Either call `await client.connect()` before any other client method, or open the client with `async with ClaudeSDKClient() as client:`, which connects on entry. + +## + +​ + +CLI process exit + +The entries in this section mean the Claude Code process ended while your application was using it. Which error you see depends on the SDK language and on whether the CLI reported an error result before it exited. + +### + +​ + +ProcessError: Command failed with exit code + +The Python SDK raises a `ProcessError` when the Claude Code process exits with a nonzero code: + + Command failed with exit code 1 (exit code: 1) + Error output: Check stderr output for details + +The message states the exit code twice, and the `Error output` line is fixed text rather than your process’s error output. The same fixed text fills the exception’s `stderr` attribute. The exception’s `exit_code` attribute carries the code. To capture what the CLI actually wrote to stderr, pass a `stderr` callback in `ClaudeAgentOptions` and log what it receives. A bare `ProcessError` means the CLI exited without reporting an error result. When the CLI did report one, the SDK raises [`ResultError`](</docs/en/agent-sdk/python#resulterror>) instead, covered in Claude Code returned an error result. `ResultError` subclasses `ProcessError`, so `except ProcessError` catches both. To handle them differently, put the `except ResultError` clause first. Before `claude-agent-sdk` 0.2.140, the Python SDK raised error-result exits as a plain `Exception` rather than a `ResultError`. + +### + +​ + +Claude Code process exited with code N + +IDE wrappers print this message too, and the [error reference](</docs/en/errors#claude-code-process-exited-with-code-n>) covers it for VS Code and other launchers. This entry covers what your TypeScript SDK code receives. The SDK surfaces a nonzero CLI exit as a plain `Error` that rejects the `for await` loop over `query()`’s messages. There’s no SDK error class to catch, so wrap the loop in `try`/`catch` and match on the message: + + Claude Code process exited with code 1. stderr: <tail of the CLI's stderr> + +When the CLI wrote to stderr, the message ends with the tail of it. To capture the full stream, pass a `stderr` callback in the query options. A process killed by a signal reports `Claude Code process terminated by signal <name>` in the same form. + +### + +​ + +Claude Code returned an error result + +Both SDKs replace the process-exit error with this message when the CLI reported an error result before exiting: + + Claude Code returned an error result: <the CLI's own error report> + +The text after the colon is the CLI’s report of what went wrong, so start there rather than with the exit itself. Python raises this as a [`ResultError`](</docs/en/agent-sdk/python#resulterror>), whose `data` attribute carries the full error result. TypeScript rejects the message loop with a plain `Error` carrying the same message shape. + ## ​
modified Agent SDK reference - TypeScript View current →
Show diff (412 lines)
--- a/typescript.md +++ b/typescript.md @@ -6,7 +6,7 @@ npm install @anthropic-ai/claude-agent-sdk -The SDK bundles a native Claude Code binary for your platform as an optional dependency such as `@anthropic-ai/claude-agent-sdk-darwin-arm64`. Most installs need no separate Claude Code install. The SDK version tracks the bundled Claude Code version: SDK v0.3.191 bundles Claude Code v2.1.191, so a feature on this page that requires a Claude Code version needs the SDK release with the same patch number or later. If your package manager skips optional dependencies, the SDK throws `Native CLI binary for <platform> not found`; set `pathToClaudeCodeExecutable` to a separately installed `claude` binary instead.If your package manager doesn’t apply npm’s `libc` field, as Yarn 1.x doesn’t, you get both the glibc and musl platform packages on Linux, roughly doubling the install size. The SDK still launches the correct variant. To reclaim the space in a container image, delete the platform package that doesn’t match the libc where your app runs; for a glibc runtime on x64, that’s `rm -rf node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl`. On a development machine the deletion is temporary, since Yarn reinstalls the package on the next dependency change. +The SDK bundles a native Claude Code binary for your platform as an optional dependency such as `@anthropic-ai/claude-agent-sdk-darwin-arm64`. Most installs need no separate Claude Code install. The SDK version tracks the bundled Claude Code version. SDK v0.3.191 bundles Claude Code v2.1.191, so a feature on this page that requires a Claude Code version needs the SDK release with the same patch number or later. If your package manager skips optional dependencies, the SDK throws `Native CLI binary for <platform>-<arch> not found`; set `pathToClaudeCodeExecutable` to a separately installed `claude` binary instead.If your package manager doesn’t apply npm’s `libc` field, as Yarn 1.x doesn’t, you get both the glibc and musl platform packages on Linux, roughly doubling the install size. On Agent SDK v0.2.141 or later, the SDK still launches the correct variant. To reclaim the space in a container image, delete the platform package that doesn’t match the libc where your app runs; for a glibc runtime on x64, that’s `rm -rf node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl`. On a development machine the deletion is temporary, since Yarn reinstalls the package on the next dependency change. ### @@ -14,7 +14,7 @@ Compile to a single executable -When you compile your application into a single-file executable with `bun build --compile`, the SDK cannot resolve the bundled CLI binary at runtime. `require.resolve` does not work inside the compiled executable’s `$bunfs` virtual filesystem, so the SDK throws `Native CLI binary for <platform> not found`. To work around this, embed the platform binary as a file asset, extract it to a real path at startup with `extractFromBunfs()`, and pass that path to `pathToClaudeCodeExecutable`. The `extractFromBunfs()` helper requires `@anthropic-ai/claude-agent-sdk` v0.3.144 or later. The example below builds for macOS on Apple Silicon: +When you compile your application into a single-file executable with `bun build --compile`, the SDK cannot resolve the bundled CLI binary at runtime. `require.resolve` does not work inside the compiled executable’s `$bunfs` virtual filesystem, so the SDK throws `Native CLI binary for <platform>-<arch> not found`. To work around this, embed the platform binary as a file asset, extract it to a real path at startup with `extractFromBunfs()`, and pass that path to `pathToClaudeCodeExecutable`. The `extractFromBunfs()` helper requires `@anthropic-ai/claude-agent-sdk` v0.3.144 or later. The example below builds for macOS on Apple Silicon: import binPath from "@anthropic-ai/claude-agent-sdk-darwin-arm64/claude" with { type: "file" }; import { extractFromBunfs } from "@anthropic-ai/claude-agent-sdk/extract"; @@ -515,7 +515,7 @@ `includeHookEvents`| `boolean`| `false`| Include hook lifecycle events in the message stream as `SDKHookStartedMessage`, `SDKHookProgressMessage`, and `SDKHookResponseMessage`. Lifecycle events for `SessionStart` and `Setup` hooks are always included and don’t need this option. Some hook events, such as `Notification`, `SessionEnd`, `PreCompact`, and `PostCompact`, never produce an `SDKHookStartedMessage`, even with this option. For those events, Claude Code still emits an `SDKHookProgressMessage` while a command hook that runs for more than a second produces output, and emits an `SDKHookResponseMessage` only when a hook [that runs in the background](</docs/en/hooks#run-hooks-in-the-background>) finishes `includePartialMessages`| `boolean`| `false`| Include partial message events `loadTimeoutMs`| `number`| `60000`| _Alpha._ Timeout in milliseconds for each `sessionStore.load()` and `sessionStore.listSubkeys()` call during resume materialization. If the adapter doesn’t settle within this window, the query fails instead of hanging. Ignored when `sessionStore` is not set -`managedSettings`| `Settings`| `undefined`| Policy-tier settings your host process supplies to the spawned session. On machines with admin-deployed managed settings, Claude Code ignores these unless the admin’s highest-priority managed source sets `parentSettingsBehavior: 'merge'`, and never merges them while a [`policyHelper`](</docs/en/settings-reference#policyhelper>) supplies managed settings. Merged values pass through a restrictive-only filter; [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>) covers what the filter admits and the `allowManaged*Only` locks +`managedSettings`| `Settings`| `undefined`| Policy-tier settings your host process supplies to the spawned session. On machines with admin-deployed managed settings, Claude Code ignores these unless the admin’s highest-priority managed source sets `parentSettingsBehavior: 'merge'`, and never merges them while a [`policyHelper`](</docs/en/settings-reference#policyhelper>) supplies managed settings. Merged values pass through a restrictive-only filter; [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>) covers what the filter admits and the `allowManaged*Only` locks. A host that sets [`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`](</docs/en/env-vars>) has three keys read straight from this payload instead: its [model configuration](</docs/en/model-config#restrict-model-selection>) on Claude Code v2.1.222 or later, [`modelPricing`](</docs/en/settings-reference#modelpricing>) when no managed source sets it on v2.1.246 or later, and its `ENABLE_TOOL_SEARCH` env entry on v2.1.247 or later `maxBudgetUsd`| `number`| `undefined`| Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for accuracy caveats `maxThinkingTokens`| `number`| `undefined`| _Deprecated:_ Use `thinking` instead. Maximum tokens for thinking process `maxTurns`| `number`| `undefined`| Maximum agentic turns (tool-use round trips) @@ -540,7 +540,7 @@ `sessionStoreFlush`| `'batched' | 'eager'`| `'batched'`| _Alpha._ Flush mode for `sessionStore`. Ignored when `sessionStore` is not set `settings`| `string | Settings`| `undefined`| Inline [settings](</docs/en/settings>) object or path to a settings file. Populates the flag-settings layer in the [precedence order](</docs/en/settings#settings-precedence>). Change at runtime with `applyFlagSettings()` `settingSources`| `SettingSource``[]`| CLI defaults (all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. [Endpoint-managed policy](</docs/en/managed-settings#delivery-mechanisms>) loads regardless; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) -`skills`| `string[] | 'all'`| `undefined`| Skills available to the session. Pass `'all'` to enable every discovered skill, or a list of skill names. Pass exact names only. The SDK rejects malformed and wildcard-form names with an error before starting the Claude Code process. When set, the SDK adds the Skill tool to `allowedTools` automatically. If you also pass `tools`, include `'Skill'` in that list. See [Skills](</docs/en/agent-sdk/skills>) +`skills`| `string[] | 'all'`| `undefined`| Skills available to the session. Pass `'all'` to enable every discovered skill, or a list of skill names. Pass exact names only. On Agent SDK v0.3.221 or later, the SDK rejects malformed and wildcard-form names with an error before starting the Claude Code process. When set, the SDK adds the Skill tool to `allowedTools` automatically. If you also pass `tools`, include `'Skill'` in that list. See [Skills](</docs/en/agent-sdk/skills>) `spawnClaudeCodeProcess`| `(options: SpawnOptions) => SpawnedProcess`| `undefined`| Custom function to spawn the Claude Code process. Use to run Claude Code in VMs, containers, or remote environments `stderr`| `(data: string) => void`| `undefined`| Callback for stderr output `strictMcpConfig`| `boolean`| `false`| Use only the servers passed in `mcpServers` and ignore project `.mcp.json`, user settings, plugin-provided MCP servers, and [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) @@ -596,7 +596,11 @@ setPermissionMode(mode: PermissionMode): Promise<void>; setModel(model?: string): Promise<void>; setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>; - applyFlagSettings(settings: { [K in keyof Settings]?: Settings[K] | null }): Promise<void>; + applyFlagSettings(settings: { + [K in keyof Settings]?: K extends 'effortLevel' + ? 'low' | 'medium' | 'high' | 'xhigh' | 'max' | null + : Settings[K] | null; + }): Promise<void>; initializationResult(): Promise<SDKControlInitializeResponse>; reinitialize(): Promise<SDKControlInitializeResponse>; supportedCommands(): Promise<SlashCommand[]>; @@ -608,6 +612,7 @@ path: string, options?: { maxBytes?: number; encoding?: 'utf-8' | 'base64' } ): Promise<SDKControlReadFileResponse | null>; + reloadSkills(): Promise<SDKControlReloadSkillsResponse>; accountInfo(): Promise<AccountInfo>; reconnectMcpServer(serverName: string): Promise<void>; toggleMcpServer(serverName: string, enabled: boolean): Promise<void>; @@ -639,10 +644,11 @@ `mcpServerStatus()`| Returns status of connected MCP servers `getContextUsage()`| Returns an `SDKControlGetContextUsageResponse` breaking down the session’s context window usage by category, skill, and tool. The same data `/context` shows in an interactive session `readFile(path, options?)`| Reads a file from the session’s filesystem. Claude Code resolves the path against `cwd` and applies the same read-permission rules as the Read tool. Pass `{ maxBytes }` to change the read cap (default 1 MB, ceiling 10 MB) and `{ encoding: 'base64' }` for binary files such as images. Resolves with an `SDKControlReadFileResponse`, or `null` on permission denial, a missing file, or a transport error. Requires TypeScript SDK v0.2.121 or later +`reloadSkills()`| Reloads skills from disk, so skills you add or edit mid-session become available to the running session. Resolves with an `SDKControlReloadSkillsResponse` listing the skills available after the reload. Requires Agent SDK v0.3.163 or later `accountInfo()`| Returns account information `reconnectMcpServer(serverName)`| Reconnect an MCP server by name `toggleMcpServer(serverName, enabled)`| Enable or disable an MCP server by name -`setMcpServers(servers)`| Dynamically replace the set of MCP servers for this session. Returns which servers were added and removed, and any errors. The call keeps plugin-provided servers it doesn’t name; naming one replaces it. The promise resolves after newly added stdio, HTTP, and SSE servers connect or fail, so tools from servers that connected are available on the next turn. +`setMcpServers(servers)`| Dynamically replace the set of MCP servers for this session. Resolves with an `McpSetServersResult` naming which servers were added and removed, and any errors `streamInput(stream)`| Stream input messages to the query for multi-turn conversations `stopTask(taskId)`| Stop a running background task by ID `close()`| Close the query and terminate the underlying process. Forcefully ends the query and cleans up all resources @@ -659,7 +665,7 @@ * **Applied during the current turn** : `model`. If you switch `model` while Claude is working on a turn, the response Claude is already generating finishes on the old model, and the rest of the turn, starting with the next call Claude Code makes to the model, uses the new one. Subagents keep their own model. Before v2.1.212, a mid-turn switch waited for the next turn. * **No effect mid-session** : the system prompt options. These are resolved once at startup, so the running session keeps the original value even though the call succeeds. To change them, start a new session. -`effortLevel` accepts an [effort level](</docs/en/model-config#adjust-effort-level>) name. It also accepts `"ultracode"`, which runs the session at `xhigh` effort and turns on [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>). The `Settings` type declares `effortLevel` without that value, so pass the equivalent `{ ultracode: true }` in TypeScript. The `ultracode` value requires Claude Code v2.1.203 or later and is accepted only by `applyFlagSettings()`, not by the `effortLevel` key in a settings file. The values are written to the flag-settings layer, the same layer the inline `settings` option of `query()` populates at startup. This is the same tier the on-page precedence section calls programmatic options. Successive calls shallow-merge top-level keys. A second call with `{ permissions: {...} }` replaces the entire `permissions` object from the prior call rather than deep-merging into it. To clear a key from the flag layer and fall back to lower-precedence sources, pass `null` for that key. Passing `undefined` has no effect because JSON serialization drops it. Only available in streaming input mode, the same constraint as `setModel()` and `setPermissionMode()`. The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify. +`effortLevel` accepts an [effort level](</docs/en/model-config#adjust-effort-level>) name. It also accepts `"ultracode"`, which runs the session at `xhigh` effort and turns on [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>). `applyFlagSettings()` declares `effortLevel` without that value, so pass the equivalent `{ ultracode: true }` in TypeScript. The `ultracode` value requires Claude Code v2.1.203 or later and is accepted only by `applyFlagSettings()`, not by the `effortLevel` key in a settings file. The values are written to the flag-settings layer, the same layer the inline `settings` option of `query()` populates at startup. This is the same tier the on-page precedence section calls programmatic options. Successive calls shallow-merge top-level keys. A second call with `{ permissions: {...} }` replaces the entire `permissions` object from the prior call rather than deep-merging into it. To clear a key from the flag layer and fall back to lower-precedence sources, pass `null` for that key. Passing `undefined` has no effect because JSON serialization drops it. Only available in streaming input mode, the same constraint as `setModel()` and `setPermissionMode()`. The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify. import { query } from "@anthropic-ai/claude-agent-sdk"; @@ -739,7 +745,7 @@ cancelled?: string[]; }; -`still_queued` lists the UUIDs of user messages that survive the interrupt: messages still in the queue, plus any batch already dequeued for the next turn but not yet reachable by the abort. Each one runs as its own turn after the interrupt unless you cancel it first. Use the receipt to decide whether to resend anything; resending a message that is already listed produces a duplicate turn. Interpret the list with these caveats: +`still_queued` lists the UUIDs of user messages that survive the interrupt: messages still in the queue, plus any messages Claude Code had already taken off the queue for the next turn before the interrupt arrived. Claude Code processes the listed messages after the interrupt unless you cancel them first, and can merge several into one turn. Use the receipt to decide whether to resend anything. Resending a message that is already listed delivers it to Claude twice. Interpret the list with these caveats: * Only messages that were enqueued with a UUID appear. An empty array doesn’t mean nothing else will run. * Only main-thread messages are listed. Messages addressed to a subagent are out of scope. @@ -877,6 +883,20 @@ ​ +`SDKControlReloadSkillsResponse` + +Return type of `reloadSkills()`. + + type SDKControlReloadSkillsResponse = { + skills: SlashCommand[]; + }; + +`skills` lists the skills available after the reload, in the same `SlashCommand` shape that `supportedCommands()` returns. + +### + +​ + `AgentDefinition` Configuration for a subagent defined programmatically. @@ -979,22 +999,7 @@ } }); -**Loading CLAUDE.md project instructions:** - - import { query } from "@anthropic-ai/claude-agent-sdk"; - - // Load project settings to include CLAUDE.md files - const result = query({ - prompt: "Add a new feature following project conventions", - options: { - systemPrompt: { - type: "preset", - preset: "claude_code" // Use Claude Code's system prompt - }, - settingSources: ["project"], // Loads CLAUDE.md from project directory - allowedTools: ["Read", "Write", "Edit"] - } - }); +To load CLAUDE.md project instructions, include `"project"` in `settingSources`. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#claude-md-files-for-project-level-instructions>) for how CLAUDE.md loading interacts with the system prompt options. #### @@ -1272,9 +1277,10 @@ aborted?: true; timestamp?: string; context_usage?: SDKContextUsage; - }; - -The `message` field is a [`BetaMessage`](<https://platform.claude.com/docs/en/api/messages/create>) from the Anthropic SDK. It includes fields like `id`, `content`, `model`, `stop_reason`, and `usage`. `SDKAssistantMessageError` is one of: `'authentication_failed'`, `'oauth_org_not_allowed'`, `'billing_error'`, `'rate_limit'`, `'overloaded'`, `'invalid_request'`, `'model_not_found'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`. `'model_not_found'` means the selected model doesn’t exist or isn’t available to your account or deployment. `'overloaded'` means the API returned a 529 because the server is at capacity, as opposed to `'rate_limit'`, which is a 429 against your quota. `aborted` is `true` when an interrupt or abort truncated the assistant message before the stream completed: the message has no `stop_reason` and the content may end mid-word. The field is absent on normally completed messages. It requires Agent SDK v0.3.214 or later. `timestamp` is the ISO 8601 time when the message’s content finished generating on the process that produced it. The value comes from that machine’s clock, so use it for display only and don’t order messages by it. One API turn can produce several assistant messages that share a `message.id`, each with its own `timestamp`. When the field is absent, fall back to the time you received the message. `context_usage` is a structured copy of the `/context` report, typed as `SDKContextUsage`, and requires Agent SDK v0.3.232 or later. When you send `/context` as a prompt, Claude Code delivers the report as an assistant message whose `message.content` holds the markdown table, and attaches `context_usage` to that same message. Claude Code doesn’t set the field on any other assistant message, and earlier versions deliver the `/context` table without it, so read the breakdown from the field when it’s present and fall back to the markdown text when it isn’t. + user_message_uuid?: string; + }; + +The `message` field is a [`BetaMessage`](<https://platform.claude.com/docs/en/api/messages/create>) from the Anthropic SDK. It includes fields like `id`, `content`, `model`, `stop_reason`, and `usage`. `SDKAssistantMessageError` is one of: `'authentication_failed'`, `'oauth_org_not_allowed'`, `'billing_error'`, `'rate_limit'`, `'overloaded'`, `'invalid_request'`, `'model_not_found'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`. `'model_not_found'` means the selected model doesn’t exist or isn’t available to your account or deployment. `'overloaded'` means the API returned a 529 because the server is at capacity, as opposed to `'rate_limit'`, which is a 429 against your quota. `aborted` is `true` when an interrupt or abort truncated the assistant message before the stream completed: the message has no `stop_reason` and the content may end mid-word. The field is absent on normally completed messages. It requires Agent SDK v0.3.214 or later. Claude Code sets `user_message_uuid` on the turn’s first assistant message, under the conditions in `user_message_uuid`. `timestamp` is the ISO 8601 time when the message’s content finished generating on the process that produced it. The value comes from that machine’s clock, so use it for display only and don’t order messages by it. One API turn can produce several assistant messages that share a `message.id`, each with its own `timestamp`. When the field is absent, fall back to the time you received the message. `context_usage` is a structured copy of the `/context` report, typed as `SDKContextUsage`, and requires Agent SDK v0.3.232 or later. When you send `/context` as a prompt, Claude Code delivers the report as an assistant message whose `message.content` holds the markdown table, and attaches `context_usage` to that same message. Claude Code doesn’t set the field on any other assistant message, and earlier versions deliver the `/context` table without it, so read the breakdown from the field when it’s present and fall back to the markdown text when it isn’t. ### @@ -1349,6 +1355,7 @@ usage: NonNullableUsage; modelUsage: { [modelName: string]: ModelUsage }; permission_denials: SDKPermissionDenial[]; + queued_turn_count?: number; structured_output?: unknown; deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> }; terminal_reason?: TerminalReason; @@ -1374,7 +1381,9 @@ usage: NonNullableUsage; modelUsage: { [modelName: string]: ModelUsage }; permission_denials: SDKPermissionDenial[]; + queued_turn_count?: number; errors: string[]; + user_message_uuid?: string; terminal_reason?: TerminalReason; fast_mode_state?: FastModeState; fast_mode_disabled_reason?: FastModeDisabledReason; @@ -1386,11 +1395,12 @@ * `api_error_status`: the HTTP status code of the API error that terminated the conversation. Absent or `null` when the turn ended without an API error. * `ttft_ms`: time to first token in milliseconds, measured when the first complete assistant message arrives. Present on the success arm only. * `ttft_stream_ms`: time in milliseconds until the first `message_start` stream event, when the response stream opens. Lower than `ttft_ms`; the gap between the two is time spent streaming the first message. Present on the success arm only. - * `user_message_uuid`: the `uuid` of the `SDKUserMessage` that started this turn, echoed back so you can match the result to the message you sent. Requires Claude Code v2.1.216 or later. Present on the success arm only, together with `request_sent_wall_ms`; absent on API-error results, subagent calls, and synthetic turns such as scheduled ones. - * `request_sent_wall_ms`: epoch milliseconds at which Claude Code dispatched the API request, for joins against server-side timestamps. Present only together with `user_message_uuid`. + * `user_message_uuid`: the `uuid` of the message you sent that started this turn. See `user_message_uuid` for which results carry it. + * `request_sent_wall_ms`: epoch milliseconds at which Claude Code dispatched the API request, for joins against server-side timestamps. Present on the success arm only, together with `user_message_uuid`, when `is_error` is false. * `usage`: main agent loop only. Excludes subagent and auxiliary model calls, and is per-turn in streaming-input sessions. Prefer `modelUsage` for token/cost accounting. * `modelUsage`: per-model totals for every model call made through the query pipeline during this `query()` call, including the main loop, subagents, and internal calls such as compaction and Workflow agents. Helper calls outside that pipeline, such as the permission classifier and token-counting requests, are excluded. In streaming-input sessions the totals are cumulative across turns, so read the latest result rather than summing across results. See [Track costs in streaming input mode](</docs/en/agent-sdk/cost-tracking#track-costs-in-streaming-input-mode>) for resets and [Recover totals after a session crash](</docs/en/agent-sdk/cost-tracking#recover-totals-after-a-session-crash>) for zeroed results. * `total_cost_usd`: cumulative estimated cost in USD for this `query()` call, covering the same calls as `modelUsage` and reset at the same points. It is an estimate, not a billing statement. See [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for accuracy caveats. + * `queued_turn_count`: the number of messages you sent with `origin: { kind: "human" }` that are still waiting when Claude Code produced the result. See `queued_turn_count` for what `0` and an absent field tell you. * `terminal_reason`: why the loop ended. One of `"completed"`, `"max_turns"`, `"tool_deferred"`, `"aborted_streaming"`, `"aborted_tools"`, `"hook_stopped"`, `"stop_hook_prevented"`, `"background_requested"`, `"blocking_limit"`, `"rapid_refill_breaker"`, `"prompt_too_long"`, `"image_error"`, `"model_error"`, `"api_error"`, `"malformed_tool_use_exhausted"`, `"budget_exhausted"`, `"structured_output_retry_exhausted"`, `"tool_deferred_unavailable"`, or `"turn_setup_failed"`. * `fast_mode_state`: one of `"on"`, `"off"`, or `"cooldown"`. * `fast_mode_disabled_reason`: why [fast mode](</docs/en/fast-mode>) isn’t available right now. Absent when nothing blocks fast mode, though a request may still run at standard speed. During the cooldown after a fast mode rate limit, Claude Code reports `fast_mode_state: "cooldown"` with no reason code and re-enables fast mode when the cooldown expires. Requires Claude Code v2.1.219 or later. @@ -1411,6 +1421,35 @@ `pending`| The availability check hasn’t completed yet The same pair of fields appears on `SDKSystemMessage` and on the `SDKControlInitializeResponse`, so you can read the fast mode state before the first turn. The `origin` field forwards the `SDKMessageOrigin` of the user message that triggered this result. When the SDK injects a synthetic follow-up turn, such as for a finished background task, the resulting `SDKResultMessage` carries `origin: { kind: "task-notification" }`. Routines whose trigger fired and server-verified messages from your other sessions arrive with this kind too, each with the `subkind` described in Task-notification subkinds. Check `kind` to distinguish results that answer your prompt from injected follow-ups before routing or suppressing them. The field is absent for results emitted before any user turn, such as startup errors. When a `PreToolUse` hook returns `permissionDecision: "defer"`, the result has `stop_reason: "tool_deferred"` and `deferred_tool_use` carries the pending tool’s `id`, `name`, and `input`. Read this field to surface the request in your own UI, then resume with the same `session_id` to continue. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) for the full round trip. + +#### + +​ + +`user_message_uuid` + +The `uuid` of the `SDKUserMessage` that started the turn, echoed so you can match Claude Code’s reply to the message you sent. Claude Code echoes it only if you set `uuid` on that message. The field is optional on `SDKUserMessage`, and a string prompt passed to `query()` carries none. When you set it, Claude Code echoes it on two kinds of frame: + + * **The result** : on the success arm with `is_error` false, together with `request_sent_wall_ms`, which requires Agent SDK v0.3.216 or later. On an error result that answers a message you sent, Claude Code echoes the field alone, which requires Agent SDK v0.3.246 or later. + * **The turn’s first reply** : the first assistant message, or with `includePartialMessages` the first stream event whose `event.type` isn’t `ping`, so you can bind the reply before the result arrives. When a turn streams nothing, Claude Code sets it on the first assistant message instead. One frame per turn carries it. Requires Agent SDK v0.3.246 or later. + +Claude Code omits the field in these cases: + + * Later assistant messages and stream events of the same turn + * Subagent frames + * Synthetic turns, such as scheduled ones + * Results with no single triggering message, such as the zeroed result after a crashed worker process + +#### + +​ + +`queued_turn_count` + +The number of messages you sent with `origin: { kind: "human" }` that are still waiting in the command queue when Claude Code produced the result. Requires Agent SDK v0.3.242 or later. What `0` and an absent field tell you: + + * **`0`** : Claude Code doesn’t count messages you sent without that `origin`, and doesn’t count task notifications, so a turn can still follow. + * **Absent** : the final result that Claude Code emits after a crash or fatal startup error omits the field, and [may carry zeroed totals](</docs/en/agent-sdk/cost-tracking#recover-totals-after-a-session-crash>). ### @@ -1474,7 +1513,10 @@ uuid: UUID; session_id: string; ttft_ms?: number; // Time to first token in ms, present only on message_start events - }; + user_message_uuid?: string; // Present on at most one stream event per turn + }; + +Claude Code sets `user_message_uuid` on one stream event per turn, under the conditions in `user_message_uuid`. ### @@ -1748,7 +1790,7 @@ Peer origin fields -A `peer` origin identifies which agent sent the message: an in-process [teammate](</docs/en/agent-teams>) sending to `main` with `SendMessage`, or a [cross-session peer](</docs/en/cross-session-messaging>), another of your Claude Code sessions. A cross-session peer can run on the same machine, or on [another of your machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>) or [Claude Code on the web](</docs/en/claude-code-on-the-web>) when its message arrives through Remote Control. The two kinds of sender fill the fields differently: +A `peer` origin identifies which agent sent the message: an in-process [teammate](</docs/en/agent-teams>) sending to `main` with `SendMessage`, or a [cross-session peer](</docs/en/cross-session-messaging>), another of your Claude Code sessions. Cross-session peers require Claude Code v2.1.224 or later on macOS and Linux; see [cross-session messaging availability](</docs/en/cross-session-messaging#availability>) for the native Windows requirement. A cross-session peer can run on the same machine, or on [another of your machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>) or [Claude Code on the web](</docs/en/claude-code-on-the-web>) when its message arrives through Remote Control. The two kinds of sender fill the fields differently: * `from`: the teammate’s name, or the sender address for a cross-session peer. For a [one-way cross-machine message](</docs/en/cross-session-messaging#message-sessions-on-other-machines>), the sender has no reply address and `from` is `"unknown"`. The value is sender-authored; `verifiedPeerPid` is the verified identity. * `fromMode`: the sending session’s permission class, `bypass` or `prompting`, declared by a host that relays a peer message between your sessions, such as the [desktop app](</docs/en/desktop#work-across-sessions>). Claude Code reads it in the receiving session when it applies the [inbound controls](</docs/en/cross-session-messaging#control-inbound-messages>). Requires Agent SDK v0.3.234 or later. @@ -2581,7 +2623,7 @@ **Tool name:** `Agent`. The previous name `Task` is still accepted as an alias, and the `tools` array in the `SDKSystemMessage` init message currently lists this tool as `Task` for backward compatibility. -The `mode` field is deprecated and ignored on Claude Code v2.1.212 or later: subagents [inherit the parent session’s permission mode](</docs/en/agent-sdk/permissions#available-modes>), and a subagent definition’s `permissionMode` can override it, except when the parent uses `bypassPermissions`, `acceptEdits`, or `auto`, and Claude Code ignores a definition’s `permissionMode: "bypassPermissions"` when bypass mode is disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>). +The `mode` field is deprecated and ignored on Claude Code v2.1.212 or later: subagents [inherit the parent session’s permission mode](</docs/en/agent-sdk/permissions#available-modes>), and a subagent definition’s `permissionMode` can override it, except when the parent uses `bypassPermissions`, `acceptEdits`, or `auto`. On v2.1.223 or later, Claude Code ignores a definition’s `permissionMode: "bypassPermissions"` when bypass mode is disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>). type AgentInput = { description: string; @@ -2708,7 +2750,7 @@ pages?: string; }; -Reads files from the local filesystem, including text, images, PDFs, and Jupyter notebooks. Use `pages` for PDF page ranges (for example, `"1-5"`). +Reads files from the local filesystem, including text, images, PDFs, and Jupyter notebooks. Use `pages` for PDF page ranges (for example, `"1-5"`). For a PDF, Claude receives the file’s contents inside the Read call’s `tool_result` content. A read that returns the `pdf` output carries a summary `text` block followed by a `document` block. One that returns the `parts` output carries the summary `text` block followed by one block per extracted page: an `image` block, or a `text` block naming the page when Claude Code couldn’t render it as an image. Before Agent SDK v0.3.242, Claude Code delivered the file’s contents as a separate `user` message after the tool result. ### @@ -2880,7 +2922,7 @@ Creates and manages a structured task list for tracking progress. -On TypeScript Agent SDK 0.3.233 and later, the following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in: +On TypeScript Agent SDK 0.3.233 and later, the following restriction applies.The following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in: * `TodoWrite` * `TaskCreate` @@ -3103,7 +3145,7 @@ stop?: boolean; }; -Schedules a one-shot wake-up that fires the given prompt after a delay. This tool backs the self-paced `/loop` command. The runtime clamps `delaySeconds` to between 60 and 3600 seconds. The `delaySeconds`, `reason`, and `prompt` fields are required unless `stop` is true. Setting `stop: true` cancels the pending wakeup and ends the self-paced `/loop`. The `stop` field requires Claude Code v2.1.202 or later. See the [ScheduleWakeup row in the tools reference](</docs/en/tools-reference>) for availability; it isn’t available on Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry, nor when you turn off [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>). +Schedules a one-shot wake-up that fires the given prompt after a delay. This tool backs the self-paced `/loop` command. The runtime clamps `delaySeconds` to between 60 and 3600 seconds. The `delaySeconds`, `reason`, and `prompt` fields are required unless `stop` is true. Setting `stop: true` cancels the pending wakeup and ends the self-paced `/loop`. The `stop` field requires Claude Code v2.1.202 or later. See the [ScheduleWakeup row in the tools reference](</docs/en/tools-reference>). ### @@ -3625,6 +3667,14 @@ count: number; outputDir: string; }; + /** Document page number of the first extracted page; labels the page images in the tool_result content. */ + firstPage?: number; + /** In-process only: the page-image bytes are delivered as image blocks in the tool_result content and aren't retained on the emitted tool_use_result, so this key is absent there. */ + pages?: { + base64: string; + mediaType: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; + error?: string; + }[]; } | { type: "file_unchanged"; @@ -3669,7 +3719,11 @@ userModified?: boolean; }; -Returns the write result with structured diff information. +Returns the write result with structured diff information. What `originalFile` and `structuredPatch` hold depends on the write: + + * For a newly created file, `originalFile` is null and `structuredPatch` is empty + * On an overwrite, `originalFile` carries the previous content, except when that content is larger than about 10 MB: Claude Code then skips the diff and returns `originalFile` null and `structuredPatch` empty + * `structuredPatch` is also empty when the write changed nothing or the diff timed out ### @@ -3861,7 +3915,7 @@ Returns the previous and updated task lists. -On TypeScript Agent SDK 0.3.233 and later, the following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in: +On TypeScript Agent SDK 0.3.233 and later, the following restriction applies.The following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in: * `TodoWrite` * `TaskCreate` @@ -4667,9 +4721,10 @@ maxOutputTokens: number; canonicalModel?: string; provider?: string; - }; - -The `canonicalModel` and `provider` fields require Claude Code v2.1.218 or later. `canonicalModel` is the canonical model ID that the pricing lookup uses; it can differ from the raw model string that keys the entry, for example when that string is a provider-specific ID or an alias. `provider` names the API backend that served the model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`. + costBasis?: 'list' | 'managed' | 'unknown'; + }; + +The `canonicalModel` and `provider` fields require Claude Code v2.1.218 or later. `canonicalModel` is the canonical model ID that the pricing lookup uses; it can differ from the raw model string that keys the entry, for example when that string is a provider-specific ID or an alias. `provider` names the API backend that served the model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`. `costBasis` names the price table that priced the model’s latest request: `list` for list price, `managed` for a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table, or `unknown` when neither matched the model ID. The field requires Claude Code v2.1.246 or later. ### @@ -4814,6 +4869,14 @@ errors: Record<string, string>; }; +When you call `setMcpServers()`, Claude Code applies these rules: + + * **Servers the call doesn’t name** : Claude Code keeps plugin-provided servers running. Requires Agent SDK v0.3.210 or later. + * **Servers the call names** : except for built-in servers the CLI started at startup, Claude Code replaces a running server only when its config differs from the one you passed. + * **Built-in servers the CLI started at startup** : if the call names one, Claude Code drops that entry and reports it in `errors`. + +The promise resolves after newly added stdio, HTTP, and SSE servers connect or fail, so tools from servers that connected are available on the next turn. + ### ​ @@ -4856,7 +4919,7 @@ `SDKTaskNotificationMessage` -Notification when a background task completes, fails, or is stopped. Background tasks include `run_in_background` Bash commands, Monitor watches, and background subagents. +Notification when a background task completes, fails, or is stopped. Background tasks include `run_in_background` Bash commands, Monitor watches, and background subagents. `ambient` is `true` for tasks Claude Code starts for its own operation; `SDKTaskStartedMessage` defines the field and its version requirement. type SDKTaskNotificationMessage = { type: "system"; @@ -4866,6 +4929,7 @@ status: "completed" | "failed" | "stopped"; output_file: string; summary: string; + ambient?: boolean; usage?: { total_tokens: number; tool_uses: number; @@ -5024,11 +5088,12 @@ task_type?: string; is_backgrounded?: boolean; spawn_depth?: number; + ambient?: boolean; uuid: UUID; session_id: string; }; -`is_backgrounded` and `spawn_depth` describe how Claude Code started the task. Both fields require Agent SDK v0.3.238 or later. +`ambient` is `true` for tasks Claude Code starts for its own operation and doesn’t display as your work, such as auto-started live-update watchers. Exclude ambient tasks from activity indicators. The field requires Agent SDK v0.3.247 or later. `ambient` also appears on `SDKTaskNotificationMessage` and on `SDKBackgroundTasksChangedMessage` entries. `is_backgrounded` and `spawn_depth` describe how Claude Code started the task. Both fields require Agent SDK v0.3.238 or later. * `is_backgrounded`: Claude Code sets it on `"local_agent"` and `"local_bash"` tasks. `true` means the task runs in the background. `false` means the task runs in the foreground, and the tool call that started it stays blocked until the task finishes or moves to the background. * `spawn_depth`: Claude Code sets it on `"local_agent"` tasks only. A subagent that the main thread spawned has depth `1`. A subagent that a depth `1` subagent spawned has depth `2`, and so on. @@ -5091,7 +5156,7 @@ `SDKBackgroundTasksChangedMessage` -Emitted whenever the set of live background tasks changes: a task starts, completes, is killed, or a foreground agent is backgrounded. The `tasks` array is the full live set. Replace any cached set with each payload instead of pairing `task_started` and `task_notification` events, so the next membership change corrects any event you missed. Ordering relative to those per-task events is unspecified, so don’t correlate the two streams. Nothing is emitted at startup. Reset to an empty set whenever the session’s CLI process starts or restarts and let the next membership change repopulate it. When you send a repeated `initialize` control request to a running session, such as with `reinitialize()` after a transport gap, Claude Code follows the response with a snapshot of the current live set, even when it is empty. A reconnecting host therefore learns what is running without waiting for the next membership change. Before Agent SDK v0.3.239, Claude Code sent no snapshot after a repeated `initialize`. Requires Claude Code v2.1.203 or later. +Emitted whenever the set of live background tasks changes: a task starts, completes, is killed, a foreground agent is backgrounded, or a task’s `ambient` flag changes. The `tasks` array is the full live set. Replace any cached set with each payload instead of pairing `task_started` and `task_notification` events, so the next membership change corrects any event you missed. Ordering relative to those per-task events is unspecified, so don’t correlate the two streams. Nothing is emitted at startup. Reset to an empty set whenever the session’s CLI process starts or restarts and let the next membership change repopulate it. When you send a repeated `initialize` control request to a running session, such as with `reinitialize()` after a transport gap, Claude Code follows the response with a snapshot of the current live set, even when it is empty. A reconnecting host therefore learns what is running without waiting for the next membership change. Before Agent SDK v0.3.239, Claude Code sent no snapshot after a repeated `initialize`. Requires Claude Code v2.1.203 or later. type SDKBackgroundTasksChangedMessage = { type: "system"; @@ -5100,6 +5165,7 @@ task_id: string; task_type: string; description: string; + ambient?: boolean; }[]; uuid: UUID; session_id: string; @@ -5237,6 +5303,8 @@ Custom error class for abort operations. class AbortError extends Error {} + +`AbortError` is the only error class in the SDK’s typed API. Other failures, such as the Claude Code process exiting or failing to launch, reject the message iteration with errors that carry no SDK class to match on. [Troubleshooting](</docs/en/agent-sdk/troubleshooting>) keys those errors by message, with the cause and fix for each. ## @@ -5371,12 +5439,7 @@ Permissions Fallback for Unsandboxed Commands -When `allowUnsandboxedCommands` is enabled, the model can request to run commands outside the sandbox by setting `dangerouslyDisableSandbox: true` in the tool input. These requests fall back to the existing permissions system, meaning your `canUseTool` handler is invoked, allowing you to implement custom authorization logic. In the example below, `isCommandAuthorized` stands in for an authorization check you define. - -**`excludedCommands` vs `allowUnsandboxedCommands`:** - - * `excludedCommands`: A static list of commands that always bypass the sandbox automatically (e.g., `['docker']`). The model has no control over this. - * `allowUnsandboxedCommands`: Lets the model decide at runtime whether to request unsandboxed execution by setting `dangerouslyDisableSandbox: true` in the tool input. +When `allowUnsandboxedCommands` is enabled, the model can request to run commands outside the sandbox by setting `dangerouslyDisableSandbox: true` in the tool input. These requests fall back to the existing permissions system, meaning your `canUseTool` handler is invoked, allowing you to implement custom authorization logic. Commands listed in `excludedCommands` instead bypass the sandbox automatically, with no model involvement; see `SandboxSettings`. In the example below, `isCommandAuthorized` stands in for an authorization check you define. import { query } from "@anthropic-ai/claude-agent-sdk";
modified Find bugs with ultrareview View current →
--- a/ultrareview.md +++ b/ultrareview.md @@ -42,7 +42,7 @@ /code-review ultra 1234 -The command also accepts `#1234`, `PR 1234`, and pasted PR URLs; a pasted URL must point to the repository in your current directory. In PR mode, the remote sandbox clones the pull request directly from the host rather than bundling your local working tree. PR mode works with repositories on `github.com` and on [GitHub Enterprise Server](</docs/en/github-enterprise-server>) instances that an Owner has connected to Claude Code. +The command also accepts `#1234`, `PR 1234`, and pasted PR URLs; a pasted URL must point to the repository in your current directory. In PR mode, the remote sandbox clones the pull request directly from the host rather than bundling your local working tree. PR mode works with repositories on `github.com` and on [GitHub Enterprise Server](</docs/en/github-enterprise-server>) instances that an Owner has connected to Claude Code. For repositories on `github.com`, the sandbox clones with the GitHub account connected to your Claude account, so the account must be able to read the PR’s repository. Claude Code checks this before creating the cloud session, unless you’ve set [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars#variables>), and refuses the launch when [no account is connected](</docs/en/errors#no-github-account-is-connected-to-your-claude-account>) or [the account can’t see the repository](</docs/en/errors#your-connected-github-account-cant-see-the-repository>); the refusal names the fix. Before v2.1.248, Claude Code didn’t check this before launch. Run [`/web-setup`](</docs/en/web-quickstart#connect-from-your-terminal>) to connect your GitHub CLI login to your Claude account. ###
modified Handle approvals and user input View current →
--- a/user-input.md +++ b/user-input.md @@ -188,27 +188,7 @@ **Allow**| `PermissionResultAllow(updated_input=...)`| `{ behavior: "allow", updatedInput }` **Deny**| `PermissionResultDeny(message=...)`| `{ behavior: "deny", message }` -When allowing, the tool runs with the input Claude requested unless you return a modified input, `updatedInput` in TypeScript or `updated_input` in Python. Before v2.1.207, Claude Code rejected an allow result that omitted `updatedInput` and denied the tool call with a validation error. When denying, provide a message explaining why. Claude sees this message and may adjust its approach. - -Python - -TypeScript - - from claude_agent_sdk.types import PermissionResultAllow, PermissionResultDeny - - # Allow the tool to execute - return PermissionResultAllow(updated_input=input_data) - - # Block the tool - return PermissionResultDeny(message="User rejected this action") - - // Allow the tool to execute - return { behavior: "allow", updatedInput: input }; - - // Block the tool - return { behavior: "deny", message: "User rejected this action" }; - -Beyond allowing or denying, you can modify the tool’s input or provide context that helps Claude adjust its approach: +When allowing, the tool runs with the input Claude requested unless you return a modified input, `updatedInput` in TypeScript or `updated_input` in Python. Before v2.1.207, Claude Code rejected an allow result that omitted `updatedInput` and denied the tool call with a validation error. When denying, provide a message explaining why. Claude sees this message and may adjust its approach. Beyond allowing or denying, you can modify the tool’s input or provide context that helps Claude adjust its approach: * **Approve** : let the tool execute as Claude requested * **Approve with changes** : modify the input before execution (e.g., sanitize paths, add constraints)
modified Use Claude Code in VS Code View current →
--- a/vs-code.md +++ b/vs-code.md @@ -118,7 +118,10 @@ Resume past conversations -Click the **Session history** button at the top of the Claude Code panel to access your conversation history. You can search by keyword or browse by time (Today, Yesterday, Last 7 days, etc.). Click any conversation to resume it with the full message history. New sessions receive AI-generated titles based on your first message. Hover over a session to reveal rename and remove actions: rename to give it a descriptive title, or remove to delete it from the list. For more on resuming sessions, see [Manage sessions](</docs/en/sessions>). +Click the **Session history** button at the top of the Claude Code panel to access your conversation history. You can search by keyword or browse by time (Today, Yesterday, Last 7 days, etc.). Click any conversation to resume it with the full message history. New sessions receive AI-generated titles based on your first message. Hover over a session to reveal rename and remove actions: rename to give it a descriptive title, or remove to delete it from the list. For more on resuming sessions, see [Manage sessions](</docs/en/sessions>). When the conversation you resume ended in plan mode, Claude Code restores plan mode. Requires Claude Code v2.1.246 or later. Claude Code doesn’t restore it in two cases: + + * The extension [chooses the starting permission mode](</docs/en/permission-modes#switch-permission-modes>) from `claudeCode.initialPermissionMode` or a pick that carries over from an earlier conversation + * You have `claudeCode.claudeProcessWrapper` configured ###
modified Orchestrate subagents at scale with dynamic workflows View current →
--- a/workflows.md +++ b/workflows.md @@ -1,4 +1,4 @@ -Dynamic workflows require Claude Code v2.1.154 or later and are available on all paid plans, with Anthropic API access, and on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry. On Pro, turn them on from the Dynamic workflows row in `/config`. +Dynamic workflows are available on all paid plans, with Anthropic API access, and on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry. On Pro, turn them on from the Dynamic workflows row in `/config`. A dynamic workflow is a JavaScript script that orchestrates [subagents](</docs/en/sub-agents>) at scale. Claude writes the script for the task you describe, and a runtime executes it in the background while your session stays responsive. Reach for a workflow when a task needs more agents than one conversation can coordinate, or when you want the orchestration codified as a script you can read and rerun. Examples include a codebase-wide bug sweep, a 500-file migration, a research question that needs sources cross-checked against each other, and a hard plan worth drafting from several independent angles before you commit to one. @@ -118,7 +118,7 @@ ultracode: audit every API endpoint under src/routes/ for missing auth checks -Claude Code highlights the keyword in your input and Claude writes a workflow script for the task instead of working through it turn by turn. The keyword only chooses how Claude structures the work: a workflow started this way runs inside the session’s existing [permission mode](</docs/en/permission-modes>), and its agents’ tool calls receive the same permission checks and [sandboxing](</docs/en/sandboxing>) as any other tool call in the session. If the run does what you wanted, you can save it as a command afterward. If you already have an orchestrator built another way, such as a folder of subagent prompts or a skill that fans work out, you can point Claude at it and ask for a workflow that does the same thing. +Claude Code highlights the keyword in your input and Claude writes a workflow script for the task instead of working through it turn by turn. The keyword only chooses how Claude structures the work: the agents’ tool calls receive the same permission checks and [sandboxing](</docs/en/sandboxing>) as any other tool call in the session. If the run does what you wanted, you can save it as a command afterward. If you already have an orchestrator built another way, such as a folder of subagent prompts or a skill that fans work out, you can point Claude at it and ask for a workflow that does the same thing. #### @@ -164,7 +164,7 @@ In the CLI, the per-run prompt shows the planned phases and these options: * **Yes, run it** : start the run - * **Yes, and don’t ask again for`<name>` in `<path>`**: start, and skip this prompt for this workflow in this project from now on + * **Yes, and don’t ask again for`<name>` in `<path>`**: start, and skip this prompt for this workflow in this project from now on. Claude Code offers this option when you run a bundled, saved, or plugin workflow by name, not for a script Claude wrote for the current task. * **View raw script** : read the script before deciding * **No** : cancel @@ -174,9 +174,18 @@ ---|--- Auto| First launch only. Any **Yes** records consent in your user settings, and later launches start without prompting. Skipped entirely when ultracode is on Manual, accept edits| Every run, unless you’ve selected **Yes, and don’t ask again** for that workflow in this project -Bypass permissions, `claude -p`, Agent SDK| Never. The run starts immediately - -In the Desktop app, an approval card shows the workflow name, the phase list, and a token-usage caution, with **Once** , **Always** , and **Deny** actions. The progress view appears in the Background tasks side pane. Your permission mode controls only the launch prompt above. The subagents the workflow spawns always run in `acceptEdits` mode and inherit your [tool allowlist](</docs/en/settings-reference#permission-settings>), regardless of your session’s mode. File edits are auto-approved. Shell commands, web fetches, and MCP tools that aren’t in your allowlist can still prompt you mid-run. To avoid this on a long run, add the commands the agents need to your allowlist before starting. In `claude -p` and the Agent SDK there is no one to prompt, so tool calls follow your configured permission rules without interactive confirmation. +Bypass permissions| Claude Code doesn’t prompt you. The run starts immediately +`claude -p`, Agent SDK| Claude Code doesn’t prompt you + +In `claude -p` and the Agent SDK, Claude Code never shows this prompt. It runs the Workflow tool call through the same [permission evaluation](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) as the rest of the session, so deny rules, ask rules, and `dontAsk` mode apply to the launch as they apply to every tool call. To let the workflow start in these runs, use one of these: + + * **Permission rule** : `Workflow` in your allow rules approves every workflow, and `Workflow(<name>)` approves one saved workflow by name. + * **Auto permission mode** : the [classifier](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) reviews the call and can approve it. + * **Bypass permissions mode** : Claude Code approves the call. + * **A`PreToolUse` hook**: a [hook](</docs/en/hooks#pretooluse>) that returns `allow` for the call approves it. + * **Your host** : a [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) approves it, or, with the Agent SDK, a [`canUseTool`](</docs/en/agent-sdk/permissions>) callback or a [`PermissionRequest` hook](</docs/en/hooks#permissionrequest>) approves it. + +In the Desktop app, an approval card shows the workflow name, the phase list, and a token-usage caution, with **Once** , **Always** , and **Deny** actions. The progress view appears in the Background tasks side pane. The subagents the workflow spawns use your [permission rules](</docs/en/settings-reference#permission-settings>), and Claude Code picks their permission mode by the rules under [which permission mode a subagent runs in](</docs/en/sub-agents#permission-modes>). To avoid prompts on a long run, add the tools the agents need to your allow rules before starting. ### @@ -356,12 +365,16 @@ Resume after a pause -If you stop a run, you can resume it. Agents that already completed usually return their cached results, and the rest run live. Two rules decide which results survive: - - * An agent that was still running when you stopped isn’t saved, so it starts over on resume. - * Replay follows the order agents started. Cached results stop at the first agent that didn’t finish, and every agent that started after that one runs again, even if it completed. - -The second rule is what makes stopping mid fan-out expensive. Say a script starts four agents, A, B, C, and D, in that order, and you stop the run while B is still going. On resume, A returns from cache. B runs again because it never finished. C and D run again too, because they started after B, even though both completed before you stopped. A workflow that fans work out across many small agents therefore preserves more progress than one long agent. Resume a paused run from `/workflows` by selecting it and pressing `p`, or ask Claude to relaunch the workflow with the same script. Resume works within the same Claude Code session. If you exit Claude Code while a workflow is running, the next session starts the workflow fresh. +Resume a paused run from `/workflows` by selecting it and pressing `p`. For a run you stopped, ask Claude to relaunch the workflow with the same script. Claude Code replays the run in the order agents started, and each agent either returns its saved result or runs again: + + * **Completed** : returns its saved result. The first agent whose prompt differs from the previous run, because you edited the script or an earlier agent returned something different, runs again, and so does every agent after it, even ones that completed. + * **Still running when you stopped** : starts over. Stopping the whole run doesn’t count any agent as failed. + * **Failed** : runs again, and so does every agent that started after it, even ones that completed. Stopping one agent alone, by selecting it in `/workflows` and pressing `x`, counts as failing. + +That last case means a failure in the middle of a fan-out reruns work that already finished. If a script starts A, B, C, and D in that order and B fails, relaunching returns A from cache and runs B, C, and D again. You can resume a run within the same Claude Code session. What happens to a running workflow when you leave the session depends on how you leave: + + * If you [background the session](</docs/en/agent-view#what-carries-over-when-you-background>), Claude Code replays the run the same way in the background session and continues it. + * If you exit Claude Code while a workflow is running and [agent view is on](</docs/en/agent-view#from-inside-a-session>), the exit dialog offers `Move to background and exit`, which carries the run over the same way. If you choose `Exit and stop tasks` instead, or the option isn’t offered, the run stops with the session. Claude Code keeps the run’s saved results under that session’s directory in `~/.claude/projects/`, so a session you resume with `claude --resume` can replay them when you ask Claude to relaunch the workflow, while a session you start fresh has nothing to replay and starts the workflow over. ###
modified Run parallel sessions with worktrees View current →
--- a/worktrees.md +++ b/worktrees.md @@ -2,7 +2,7 @@ Worktrees require a git repository; for other version control systems, configure hooks to replace the git logic. In the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), every new session gets its own worktree automatically. -Worktrees are one of several ways to run Claude in parallel. They isolate file edits, while [subagents](</docs/en/sub-agents>) and [agent teams](</docs/en/agent-teams>) coordinate the work itself. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. Most sessions need only the first two sections: start Claude in a worktree, then clean up when you exit. Return to the rest of the page when you need to resume a session, change how worktrees are created, or debug a failure. +Worktrees are one of several ways to run Claude in parallel. They isolate file edits. [Subagents](</docs/en/sub-agents>) split work up inside one session, and [cross-session messaging](</docs/en/cross-session-messaging>) lets Claude pass findings between the sessions in your worktrees. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. Most sessions need only the first two sections: start Claude in a worktree, then clean up when you exit. Return to the rest of the page when you need to resume a session, change how worktrees are created, or debug a failure. ## @@ -115,7 +115,7 @@ * The worktree belongs to a `--worktree` session you haven’t backgrounded, whatever its age. * You created the worktree yourself with `git worktree add`, even if you then ran a `--worktree <name>` session in it and backgrounded that session. -Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. Before v2.1.246, the sweep didn’t check for the marker, and could remove a worktree you created yourself when an old background-session record pointed at it. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. +Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. Before v2.1.246, the sweep didn’t check for the marker, and could remove a worktree you created yourself when an old background-session record pointed at it. While an agent is running, Claude Code holds a `git worktree lock` on its worktree so that concurrent cleanup can’t remove it, and releases the lock when the agent finishes. Claude Code holds the same lock on the worktree it created for a backgrounded session while the session runs, so the sweep leaves the worktree in place and `git worktree remove` refuses to remove it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. ## @@ -217,7 +217,7 @@ * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory, and [sandboxing](</docs/en/sandboxing#filesystem-isolation>) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled. * **Plugins** : plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. Requires Claude Code v2.1.200 or later. - * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and the other cases where Claude Code [keeps the local file in the starting directory](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). + * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). All three apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). @@ -356,9 +356,10 @@ See also -Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts and switching between the sessions you create: +Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts, passing findings between them, and switching between the sessions you create: * [Subagents](</docs/en/sub-agents>): delegate work to isolated agents within a session + * [Cross-session messaging](</docs/en/cross-session-messaging>): let the sessions in your worktrees pass findings to each other * [Agent teams](</docs/en/agent-teams>): coordinate multiple Claude sessions automatically * [Manage sessions](</docs/en/sessions>): name, resume, and switch between conversations * [Desktop parallel sessions](</docs/en/desktop#work-in-parallel-with-sessions>): worktree-backed sessions in the desktop app