modified Set up Claude Code for your organization View current →
--- a/admin-setup.md +++ b/admin-setup.md @@ -51,7 +51,7 @@ Windows: `C:\Program Files\ClaudeCode\managed-settings.json`| Medium| All Windows user registry| `HKCU\SOFTWARE\Policies\ClaudeCode`| Lowest| Windows only -A configured [`policyHelper`](</docs/en/settings#compute-managed-settings-with-a-policy-helper>) preempts all four sources: its output becomes the only managed configuration for the run. See [Settings precedence](</docs/en/settings#settings-precedence>). Server-managed settings reach devices at authentication time and refresh hourly during active sessions, with no endpoint infrastructure. Delivery through the claude.ai admin console requires a Claude for Teams or Enterprise plan. Deployments on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry can get the same remote delivery by running a [Claude apps gateway](</docs/en/claude-apps-gateway>), or use one of the file-based or OS-level mechanisms instead. If your organization mixes providers, configure [server-managed settings](</docs/en/server-managed-settings>) for claude.ai users plus a [file-based or plist/registry fallback](</docs/en/settings#settings-files>) so other users still receive managed policy. The plist and HKLM registry locations work with any provider and resist tampering because they require admin privileges to write. The Windows user registry at HKCU is writable without elevation, so treat it as a convenience default rather than an enforcement channel. By default, WSL reads only the Linux file path at `/etc/claude-code`. To extend your Windows registry and `C:\Program Files\ClaudeCode` policy to WSL on the same machine, set [`wslInheritsWindowsSettings: true`](</docs/en/settings#available-settings>) in either of those admin-only Windows sources. Whichever mechanism you choose, managed values take precedence over user and project settings, apart from the exceptions under [Settings precedence](</docs/en/settings#settings-precedence>). Array settings such as `permissions.allow` and `permissions.deny` merge entries from all sources, so developers can extend managed lists but not remove from them. For [two exceptions](</docs/en/settings#settings-precedence>), `fallbackModel` and `availableModels`, the managed value replaces lower layers rather than merging. See [Server-managed settings](</docs/en/server-managed-settings>) and [Settings files and precedence](</docs/en/settings#settings-files>). +Server-managed settings reach devices at authentication time and refresh hourly during active sessions, with no endpoint infrastructure. Delivery through the claude.ai admin console requires a Claude for Teams or Enterprise plan. Deployments on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry can get the same remote delivery by running a [Claude apps gateway](</docs/en/claude-apps-gateway>), or use one of the file-based or OS-level mechanisms instead. If your organization mixes providers, configure [server-managed settings](</docs/en/server-managed-settings>) for claude.ai users plus a [file-based or plist/registry fallback](</docs/en/settings#settings-files>) so other users still receive managed policy. The plist and HKLM registry locations work with any provider and resist tampering because they require admin privileges to write. The Windows user registry at HKCU is writable without elevation, so treat it as a convenience default rather than an enforcement channel. By default, WSL reads only the Linux file path at `/etc/claude-code`. To extend your Windows registry and `C:\Program Files\ClaudeCode` policy to WSL on the same machine, set [`wslInheritsWindowsSettings: true`](</docs/en/settings#available-settings>) in either of those admin-only Windows sources. Whichever mechanism you choose, managed values take precedence over user and project settings, apart from the exceptions under [Settings precedence](</docs/en/settings#settings-precedence>). Array settings such as `permissions.allow` and `permissions.deny` merge entries from all sources, so developers can extend managed lists but not remove from them. For [two exceptions](</docs/en/settings#settings-precedence>), `fallbackModel` and `availableModels`, the managed value replaces lower layers rather than merging. See [Server-managed settings](</docs/en/server-managed-settings>) and [Settings files and precedence](</docs/en/settings#settings-files>). ###
modified Escalate hard decisions with the advisor tool View current →
--- a/advisor.md +++ b/advisor.md @@ -154,7 +154,7 @@ /advisor off -To disable the advisor tool entirely, set `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1`. The `/advisor` command becomes unavailable and any configured `advisorModel` is ignored. The `--advisor` flag is accepted but has no effect; existing scripts that pass it continue to work without errors. See [Environment variables](</docs/en/env-vars>). +To disable the advisor tool entirely, set `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1`. The `/advisor` command becomes unavailable and any configured `advisorModel` is ignored. The `--advisor` flag is accepted but has no effect. See [Environment variables](</docs/en/env-vars>). ##
modified How the agent loop works View current →
--- a/agent-loop.md +++ b/agent-loop.md @@ -314,7 +314,7 @@ Sessions and continuity -Each interaction with the SDK creates or continues a session. Capture the session ID from `ResultMessage.session_id` (available in both SDKs) to resume later. The TypeScript SDK also exposes it as a direct field on the init `SystemMessage`; in Python it’s nested in `SystemMessage.data`. When you resume, the full context from previous turns is restored: files that were read, analysis that was performed, and actions that were taken. You can also fork a session to branch into a different approach without modifying the original. See [Session management](</docs/en/agent-sdk/sessions>) for the full guide on resume, continue, and fork patterns. To resume sessions across stateless containers or serverless hosts, pass a [`session_store` / `sessionStore` adapter](</docs/en/agent-sdk/session-storage>) so transcripts are mirrored to your own backend and any host can resume them. The Claude Code subprocess still writes to local disk first; point `CLAUDE_CONFIG_DIR` at a temp directory in `options.env` if the local copy needs to be ephemeral. +Each interaction with the SDK creates or continues a session. Capture the session ID from `ResultMessage.session_id` (available in both SDKs) to resume later. The TypeScript SDK also exposes it as a direct field on the init `SystemMessage`; in Python it’s nested in `SystemMessage.data`. When you resume, the full context from previous turns is restored: files that were read, analysis that was performed, and actions that were taken. You can also fork a session to branch into a different approach without modifying the original. See [Session management](</docs/en/agent-sdk/sessions>) for the full guide on resume, continue, and fork patterns. To resume sessions across stateless containers or serverless hosts, pass a [`session_store` / `sessionStore` adapter](</docs/en/agent-sdk/session-storage>) so the SDK mirrors transcripts to your own backend and any host can resume them. The Claude Code subprocess still writes to local disk first. See [Dual-write architecture](</docs/en/agent-sdk/session-storage#dual-write-architecture>) for which copy outlives a fresh session versus a run resumed from the store, and how to keep the local copy ephemeral. In Python, `ClaudeSDKClient` handles session IDs automatically across multiple calls. See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claudesdkclient>) for details. @@ -334,14 +334,19 @@ `error_during_execution`| An error interrupted the loop (for example, an API failure or cancelled request)| No `error_max_structured_output_retries`| No valid structured output was produced within the configured retry limit: every attempt failed validation, or a model fallback retracted the completed output with no successful retry| No -The `result` field (the final text output) is only present on the `success` variant, so always check the subtype before reading it. All result subtypes carry `total_cost_usd`, `usage`, `num_turns`, and `session_id` so you can track cost and resume even after errors. In Python, `total_cost_usd` and `usage` are typed as optional and may be `None` on some error paths, so guard before formatting them. See [Tracking costs and usage](</docs/en/agent-sdk/cost-tracking>) for details on interpreting the `usage` fields. +The `result` field holds the final text output and is only present on the `success` variant, so always check the subtype before reading it. All result subtypes carry `total_cost_usd`, `usage`, `num_turns`, and `session_id` so you can track cost and resume even after errors. Two things to guard for: + + * After a session crash, the final result is an `error_during_execution` whose cost fields may be zeroed and whose `stop_reason` is `null`, and the process exits after emitting it. See [Recover totals after a session crash](</docs/en/agent-sdk/cost-tracking#recover-totals-after-a-session-crash>). + * In Python, `total_cost_usd`, `usage`, and `model_usage` are typed as optional, so check that they aren’t `None` before you read them. + +The `usage` field covers only the main agent loop. Use `modelUsage`, or `model_usage` in Python, for whole-tree token and cost accounting. See [Tracking costs and usage](</docs/en/agent-sdk/cost-tracking>) for details on interpreting the `usage` fields. When a query ends on an error result: * A single-shot `query()` call yields the final result message, then raises an error that includes the failure text, such as `Reached maximum number of turns`. The raise is intentional — wrap the loop in a try block if your code needs to continue past it. The underlying Claude Code process also exits with a nonzero code. - * A streaming input session stays alive, and you can keep sending messages. - -The result also includes a `stop_reason` field (`string | null` in TypeScript, `str | None` in Python) indicating why the model stopped generating on its final turn. Common values are `end_turn` (model finished normally), `max_tokens` (hit the output token limit), and `refusal` (the model declined the request). On error result subtypes, `stop_reason` carries the value from the last assistant response before the loop ended. To detect refusals, check `stop_reason === "refusal"` (TypeScript) or `stop_reason == "refusal"` (Python). See [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) (TypeScript) or [`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>) (Python) for the full type. + * A streaming input session stays alive, and you can keep sending messages, except after a session crash, which emits a final `error_during_execution` result and exits the process. + +The result also includes a `stop_reason` field (`string | null` in TypeScript, `str | None` in Python) indicating why the model stopped generating on its final turn. Common values are `end_turn` (model finished normally), `max_tokens` (hit the output token limit), and `refusal` (the model declined the request). On error results that the loop produced, `stop_reason` carries the value from the last assistant response before the loop ended; the result Claude Code synthesizes after a session crash carries `null`. To detect refusals, check `stop_reason === "refusal"` (TypeScript) or `stop_reason == "refusal"` (Python). See [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) (TypeScript) or [`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>) (Python) for the full type. ##
modified Orchestrate teams of Claude Code sessions View current →
--- a/agent-teams.md +++ b/agent-teams.md @@ -228,12 +228,12 @@ **Task list**| Shared list of work items that teammates claim and complete **Mailbox**| Messaging system for communication between agents -See Choose a display mode for display configuration options. Teammate messages arrive at the lead automatically. Each agent’s mailbox is a JSON file at `~/.claude/teams/{team-name}/inboxes/{agent-name}.json`. Claude Code validates every entry when it reads a mailbox file. Entries that don’t match the message format are reported as errors and removed from the file; the valid messages are still delivered. Before v2.1.207, a single malformed mailbox entry caused a repeated error every second and blocked delivery for that mailbox until you deleted the file manually. Claude Code manages task dependencies automatically: when a teammate completes a task that other tasks depend on, it unblocks the dependent tasks without any action from you. Teams and tasks are stored locally under a session-derived name. The name is `session-` followed by the first eight characters of the session ID: +See Choose a display mode for display configuration options. Teammate messages arrive at the lead automatically. Each agent’s mailbox is a JSON file at `~/.claude/teams/{team-name}/inboxes/{agent-name}.json`. Claude Code validates every entry when it reads a mailbox file. Entries that don’t match the message format are reported as errors and removed from the file; the valid messages are still delivered. Before v2.1.207, a single malformed mailbox entry caused a repeated error every second and blocked delivery for that mailbox until you deleted the file manually. Claude Code reports a message as sent only when the write to the recipient’s mailbox file succeeds, whether the message is plain text or a structured protocol message such as a plan approval or shutdown request. When the write fails, for example because the disk is full or the mailbox directory isn’t writable, the sending agent receives an error and nothing is sent. See [Failed to write to a teammate’s inbox](</docs/en/errors#failed-to-write-to-a-teammate-inbox>) for the error messages and recovery steps. Claude Code manages task dependencies automatically: when a teammate completes a task that other tasks depend on, it unblocks the dependent tasks without any action from you. Teams and tasks are stored locally under a session-derived name. The name is `session-` followed by the first eight characters of the session ID: * **Team config** : `~/.claude/teams/{team-name}/config.json` * **Task list** : `~/.claude/tasks/{team-name}/` -Claude Code generates both of these automatically at session startup and updates them as teammates join, go idle, or leave. The team config directory is removed when the session ends. The task list directory persists locally and is never uploaded, so resumed sessions keep their tasks. Retention is governed by the same [`cleanupPeriodDays`](</docs/en/settings#available-settings>) you already control for session transcripts. The team config holds runtime state such as session IDs and tmux pane IDs, so don’t edit it by hand or pre-author it: your changes are overwritten on the next state update. To define reusable teammate roles, use subagent definitions instead. The team config contains a `members` array with each member’s name and agent ID. The lead’s entry always carries the agent type `team-lead`. A teammate’s entry carries whatever agent type the lead named when spawning it, whether a [built-in type](</docs/en/sub-agents#built-in-subagents>) or a subagent definition, and omits the field when the lead named none. Teammates can read this file to discover other team members. There is no project-level equivalent of the team config. A file like `.claude/teams/teams.json` in your project directory is not recognized as configuration; Claude treats it as an ordinary file. +Claude Code generates both of these automatically at session startup and updates them as teammates join, go idle, or leave. The team config directory is removed when the session ends. The task list directory persists locally and is never uploaded, so resumed sessions keep their tasks. Retention is governed by the same [`cleanupPeriodDays`](</docs/en/settings#available-settings>) you already control for session transcripts, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). The team config holds runtime state such as session IDs and tmux pane IDs, so don’t edit it by hand or pre-author it: your changes are overwritten on the next state update. To define reusable teammate roles, use subagent definitions instead. The team config contains a `members` array with each member’s name and agent ID. The lead’s entry always carries the agent type `team-lead`. A teammate’s entry carries whatever agent type the lead named when spawning it, whether a [built-in type](</docs/en/sub-agents#built-in-subagents>) or a subagent definition, and omits the field when the lead named none. Teammates can read this file to discover other team members. There is no project-level equivalent of the team config. A file like `.claude/teams/teams.json` in your project directory is not recognized as configuration; Claude treats it as an ordinary file. ###
modified Manage multiple agents with agent view View current →
--- a/agent-view.md +++ b/agent-view.md @@ -1,6 +1,6 @@ Agent view, opened with `claude agents`, is one screen for all your background sessions: what’s running, what needs your input, and what’s done. Dispatch new sessions, watch their state at a glance instead of scrolling through transcripts, and step in only when one needs you. Each background session is a full Claude Code conversation that keeps running without a terminal attached, so you can open it, reply, and leave whenever you want. Use agent view when you have several independent tasks Claude can work on without you watching every step. Dispatch a bug fix, a pull request review, and a flaky-test investigation as three rows, keep working in another window, and check back when a row shows it needs you or has a result. When you want to work more directly in any agent’s session, attach to the row to enter the full conversation. To compare agent view with subagents, agent teams, and worktrees, see [Run agents in parallel](</docs/en/agents>). -Agent view is in research preview and requires Claude Code v2.1.139 or later. Check your version with `claude --version`. The interface and keyboard shortcuts may change as the feature evolves. +Agent view is in research preview. The interface and keyboard shortcuts may change as the feature evolves. ## @@ -18,7 +18,7 @@ claude agents -Agent view opens with an input at the bottom and a table that fills in as sessions start. Press `Esc` at any time to return to your shell; if you opened agent view by backgrounding a session with `←`, `Esc` returns to that conversation instead. Your sessions keep running while you’re away and reappear the next time you open agent view. +If you haven’t yet accepted the [workspace trust dialog](</docs/en/permissions#project-allow-rules-and-workspace-trust>) for the directory, Claude Code shows it before agent view opens, the same dialog `claude` shows. Accept to save trust for the workspace and continue. If you decline, Claude Code exits without opening agent view.Agent view opens with an input at the bottom and a table that fills in as sessions start. Press `Esc` at any time to return to your shell; if you opened agent view by backgrounding a session with `←`, `Esc` returns to that conversation instead. Your sessions keep running while you’re away and reappear the next time you open agent view. 2 @@ -287,7 +287,7 @@ A directory whose name contains a space isn’t listed. * From the shell, `cd` into the directory and run `claude --bg "<prompt>"`. -When agent view is grouped by directory, the highlighted row’s directory becomes the dispatch target, so you can scroll to a group and dispatch into it without retyping the path. +When agent view is grouped by directory, dispatching sends the prompt to the selected row’s directory, so you can select a group and dispatch into it without retyping the path. ### @@ -381,7 +381,7 @@ How file edits are isolated -Every background session, whether started from agent view, `/bg`, or `claude --bg`, starts in your working directory. Before editing files, Claude moves the session into an isolated [git worktree](</docs/en/worktrees>) under `.claude/worktrees/`, so parallel sessions can read the same checkout but each writes to its own. Once the session is in its worktree, Claude Code [blocks file edits and commands that reach the main checkout](</docs/en/worktrees#how-claude-code-enforces-isolation>), for the session and for any subagents it spawns. Claude skips the worktree when: +Every background session, whether started from agent view, `/bg`, or `claude --bg`, starts in your working directory. Before editing files, Claude moves the session into an isolated [git worktree](</docs/en/worktrees>) under `.claude/worktrees/`, so parallel sessions can read the same checkout but each writes to its own. Once the session is in its worktree, Claude Code [enforces worktree isolation](</docs/en/worktrees#how-claude-code-enforces-isolation>) for the session and for any subagents it spawns. Claude skips the worktree when: * The session is already inside a linked git worktree, whether Claude created it under `.claude/worktrees/` or you created it with `git worktree add` somewhere else * The working directory isn’t a git repository and no [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) is configured @@ -734,6 +734,9 @@ Version| Change ---|--- +v2.1.225| `claude agents` in a directory you haven’t trusted shows the same [workspace trust dialog](</docs/en/permissions#project-allow-rules-and-workspace-trust>) that `claude` shows on startup, before agent view opens. Accepting saves trust for that workspace; declining exits without opening agent view. Before this release, `claude agents` opened without asking, so sessions you dispatched from it ran in a directory you’d never been asked to trust. + +With the list grouped by directory, hovering the mouse over a row highlights it without changing the dispatch target; selecting a row with the arrow keys or a click still changes the target. Before this release, moving the mouse over a session in another project silently changed the directory the next dispatched session started in. v2.1.221| `/status` shows a `Session kind` row: `background job · attached` or `background job · unattended` in a background session, depending on whether a terminal is attached, and `interactive` in any other session. Before this release, `/status` didn’t report the session kind. `/fork`: Claude Code instructs the copy to isolate its work from the original session’s: the copy creates a worktree of its own before making code changes, stays out of the original session’s worktree, and bases a new branch on the original’s branch when its task builds on that work. See the linked section for the exact conditions. Before this release, the copy received no isolation instruction and could end up editing the worktree or checkout the original session was still working in.
modified Claude Code on Amazon Bedrock View current →
--- a/amazon-bedrock.md +++ b/amazon-bedrock.md @@ -102,7 +102,7 @@ Credential caching and resolution timeout -Claude Code resolves the AWS default credential provider chain once and keeps the resolved credentials in memory. It reuses them until five minutes before they expire, or for one hour when they carry no expiration, so an SSO-backed profile requests credentials from IAM Identity Center about once per credential lifetime. A credential error from the API clears the cache, and the retry resolves fresh credentials. Before v2.1.207, Claude Code resolved the chain on every API request, so an SSO-backed profile requested fresh credentials from IAM Identity Center each time and could be throttled in large deployments. The cache covers every credential option above except an Amazon Bedrock API key, which doesn’t use the provider chain. To resolve the chain on every request instead, set [`CLAUDE_CODE_SKIP_AWS_CRED_CACHE=1`](</docs/en/env-vars>). Each resolve of the chain times out after 60 seconds. If a step in the chain stalls, for example a `credential_process` helper that waits for input it can’t receive, the request fails with [`AWS default-chain credential resolve timed out`](</docs/en/errors#aws-default-chain-credential-resolve-timed-out>). If your chain runs an interactive sign-in that legitimately needs longer, such as browser-based SSO with MFA through a wrapper like `aws-vault`, raise the limit in milliseconds with [`CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS`](</docs/en/env-vars>). Before v2.1.207, a stalled credential resolution left the request waiting indefinitely. +Claude Code resolves the AWS default credential provider chain once and keeps the resolved credentials in memory. It reuses them until five minutes before they expire, or for one hour when they carry no expiration, so an SSO-backed profile requests credentials from IAM Identity Center about once per credential lifetime. A credential error from the API clears the cache, and the retry resolves fresh credentials. Requires Claude Code v2.1.207 or later. The cache covers every credential option above except an Amazon Bedrock API key, which doesn’t use the provider chain. To resolve the chain on every request instead, set [`CLAUDE_CODE_SKIP_AWS_CRED_CACHE=1`](</docs/en/env-vars>). Each resolve of the chain times out after 60 seconds. If a step in the chain stalls, for example a `credential_process` helper that waits for input it can’t receive, the request fails with [`AWS default-chain credential resolve timed out`](</docs/en/errors#aws-default-chain-credential-resolve-timed-out>). If your chain runs an interactive sign-in that legitimately needs longer, such as browser-based SSO with MFA through a wrapper like `aws-vault`, raise the limit in milliseconds with [`CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS`](</docs/en/env-vars>). Before v2.1.207, a stalled credential resolution left the request waiting indefinitely. #### @@ -126,7 +126,7 @@ ##### Configuration settings explained -**`awsAuthRefresh`** : Use this for commands that modify the `.aws` directory, such as updating credentials, SSO cache, or config files. The command’s output is displayed to the user, but interactive input isn’t supported. This works well for browser-based SSO flows where the CLI displays a URL or code and you complete authentication in the browser. **`awsCredentialExport`** : Only use this if you can’t modify `.aws` and must directly return credentials. This command runs whenever credentials need to be refreshed, not only when credentials are expired. Output is captured silently and not shown to the user. The command must output JSON in this format: +**`awsAuthRefresh`** : Use this for commands that modify the `.aws` directory, such as updating credentials, SSO cache, or config files. The command’s output is displayed to the user, but interactive input isn’t supported. This works well for browser-based SSO flows where the CLI displays a URL or code and you complete authentication in the browser. **`awsCredentialExport`** : Only use this if you can’t modify `.aws` and must directly return credentials. Output is captured silently and not shown to the user. The command must output JSON in this format: { "Credentials": { @@ -137,7 +137,7 @@ } } -As of Claude Code v2.1.181, the flat output from `aws configure export-credentials --format process` is also accepted, with the same keys at the top level instead of nested under `Credentials`. `Expiration` is optional. As of Claude Code v2.1.176, when the command returns a valid ISO 8601 `Expiration`, Claude Code caches the credentials until five minutes before that time. Without it, or on earlier versions, credentials are cached for one hour. When you configure `awsCredentialExport` without `awsAuthRefresh`, Claude Code uses the exported credentials directly and doesn’t re-resolve the AWS default credential provider chain at startup. Before v2.1.206, startup also re-resolved the default provider chain, which made a live SSO or STS call outside your proxy configuration and could block the first prompt for several minutes on networks with restricted egress. +As of Claude Code v2.1.181, the flat output from `aws configure export-credentials --format process` is also accepted, with the same keys at the top level instead of nested under `Credentials`. `Expiration` is optional. As of Claude Code v2.1.176, when the command returns a valid ISO 8601 `Expiration`, Claude Code caches the credentials until five minutes before that time. Without it, or on earlier versions, credentials are cached for one hour. When you configure `awsCredentialExport` without `awsAuthRefresh`, Claude Code uses the exported credentials directly and doesn’t re-resolve the AWS default credential provider chain at startup. Requires Claude Code v2.1.206 or later. ### @@ -251,8 +251,6 @@ Startup model checks When Claude Code starts with Amazon Bedrock configured, it verifies that the models it intends to use are accessible in your account. If you have pinned a model version that is older than the current Claude Code default, and your account can invoke the newer version, Claude Code prompts you to update the pin. Accepting writes the new model ID to your [user settings file](</docs/en/settings>) and restarts Claude Code. Declining is remembered until the next default version change. Pins that point to an application inference profile ARN are skipped, since those are managed by your administrator. If you have not pinned a model and the current default is unavailable in your account, Claude Code falls back for the current session and shows a notice. It tries earlier versions of the default model first and, when the default is an Opus model and no Opus version is available, falls back to the default Sonnet model. The fallback is not persisted. Enable the newer model in your Amazon Bedrock account or pin a version to make the choice permanent. When you start the session on a specific Sonnet or Opus version, with `--model`, `ANTHROPIC_MODEL`, or the [`model` setting](</docs/en/settings>), that version acts as the session’s pinned default for the matching `sonnet` or `opus` alias. Claude Code skips the availability check for the built-in default your model replaces and starts on the model you configured, with no fallback notice. Model aliases such as `opus` don’t act as pins, and neither does a model ID Claude Code doesn’t recognize, such as an application inference profile ARN. - -Before v2.1.211, Claude Code checked the default model’s availability even when a session model was explicitly configured, and could show a fallback notice for a default the session didn’t use. ##
modified Authentication View current →
--- a/authentication.md +++ b/authentication.md @@ -146,7 +146,11 @@ * **The`env` block**: [merges per key](</docs/en/server-managed-settings#per-key-exceptions-across-managed-sources>) in Claude Code v2.1.223 or later * **The[cross-source lock keys](</docs/en/server-managed-settings#per-key-exceptions-across-managed-sources>)**: honored from any admin source -`forceLoginMethod` and `forceLoginOrgUUID` are neither, so keep them in both places. The keys also block sessions authenticated by `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper`, since organization membership can’t be verified for an environment credential. Cloud provider sessions such as Amazon Bedrock authenticate against your cloud provider and aren’t blocked; restrict those through your cloud IAM policies. See [`forceLoginOrgUUID`](</docs/en/settings#available-settings>) in the settings reference for the full behavior. Before v2.1.146, the pin applied only to the login flow and didn’t block API-key credentials. +`forceLoginMethod` and `forceLoginOrgUUID` are neither, so keep them in both places. The keys also decide whether a session that doesn’t use a login credential can start. See [`forceLoginOrgUUID`](</docs/en/settings#available-settings>) in the settings reference for the full behavior. + + * **`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper`**: blocked at startup, since organization membership can’t be verified for an environment credential. Before v2.1.146, the pin applied only to the login flow and didn’t block API-key credentials + * **Cloud provider sessions such as Amazon Bedrock** : not blocked, because they authenticate against your cloud provider. Restrict those through your cloud IAM policies + * **Anthropic profile or federation credentials** : not blocked, and the keys don’t check which organization the profile belongs to ## @@ -162,7 +166,7 @@ * On Windows, credentials are stored in `%USERPROFILE%\.claude\.credentials.json` and inherit the access controls of your user profile directory, which restricts the file to your user account by default. * If you’ve set the `CLAUDE_CONFIG_DIR` environment variable on Linux or Windows, the `.credentials.json` file lives under that directory instead. * Claude Code manages `.credentials.json` through `/login` and `/logout`. To route requests through a custom API endpoint, set the [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) environment variable instead. - * **Supported authentication types** : Claude.ai credentials, Claude API credentials, Microsoft Foundry Auth, Bedrock Auth, Vertex Auth, and [Claude apps gateway](</docs/en/claude-apps-gateway>) session tokens. + * **Supported authentication types** : Claude.ai credentials, Claude API credentials, Microsoft Foundry Auth, Bedrock Auth, Vertex Auth, Anthropic profile and [Workload Identity Federation](<https://platform.claude.com/docs/en/manage-claude/workload-identity-federation>) credentials, and [Claude apps gateway](</docs/en/claude-apps-gateway>) session tokens. * **Custom credential scripts** : configure the [`apiKeyHelper`](</docs/en/settings#available-settings>) setting to run a shell script that returns an API key. * **Refresh intervals** : by default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals. * **Slow helper notice** : if `apiKeyHelper` takes longer than 10 seconds to return a key, Claude Code displays a warning notice in the prompt bar showing the elapsed time. If you see this notice regularly, check whether your credential script can be optimized. @@ -191,9 +195,29 @@ 3. `ANTHROPIC_API_KEY` environment variable. Sent as the `X-Api-Key` header. Use this for direct Anthropic API access with a key from the [Claude Console](<https://platform.claude.com>). In interactive mode, you are prompted once to approve or decline the key, and your choice is remembered. To change it later, use the “Use custom API key” toggle in `/config`. The toggle only appears while `ANTHROPIC_API_KEY` is set in your environment. In non-interactive mode (`-p`), the key is always used when present. 4. [`apiKeyHelper`](</docs/en/settings#available-settings>) script output. Use this for dynamic or rotating credentials, such as short-lived tokens fetched from a vault. 5. `CLAUDE_CODE_OAUTH_TOKEN` environment variable. A long-lived OAuth token generated by `claude setup-token`. Use this for CI pipelines and scripts where browser login isn’t available. - 6. Subscription OAuth credentials from `/login`. This is the default for Claude Pro, Max, Team, and Enterprise users. - -A signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) session sits outside this list: it is a provider selection like Amazon Bedrock or Google Cloud’s Agent Platform, and it outranks them. When a gateway session exists, the CLI authenticates with the gateway token even if `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY` is set, and the bearer token, API key, and `apiKeyHelper` entries above are not used. If you have an active Claude subscription but also have `ANTHROPIC_API_KEY` set in your environment, the API key takes precedence once approved. This can cause authentication failures if the key belongs to a disabled or expired organization. Run `unset ANTHROPIC_API_KEY` to fall back to your subscription, and check `/status` to confirm which method is active. The `Login method` row shows your subscription account, and an `API key` row appears when an API key is in use. [Claude Code on the Web](</docs/en/claude-code-on-the-web>) always uses your subscription credentials. If you set `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in the sandbox environment, it doesn’t override your subscription credentials. + 6. Anthropic profile and federation credentials, the credentials that the `ant` CLI and Workload Identity Federation use. A profile that `ant auth login` wrote ranks here only when you name it in `ANTHROPIC_PROFILE`; otherwise it ranks below `/login`. See Anthropic profiles and federation credentials. + 7. Subscription OAuth credentials from `/login`. This is the default for Claude Pro, Max, Team, and Enterprise users. + +A signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) session sits outside this list: it is a provider selection like Amazon Bedrock or Google Cloud’s Agent Platform, and it outranks them. When a gateway session exists, the CLI authenticates with the gateway token even if `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY` is set, and credential sources above such as the bearer token, API key, `apiKeyHelper`, and profiles are not used. If you have an active Claude subscription but also have `ANTHROPIC_API_KEY` set in your environment, the API key takes precedence once approved. This can cause authentication failures if the key belongs to a disabled or expired organization. Run `unset ANTHROPIC_API_KEY` to fall back to your subscription, and check `/status` to confirm which method is active. The `Login method` row shows your subscription account, and an `API key` row appears when an API key is in use. [Claude Code on the Web](</docs/en/claude-code-on-the-web>) always uses your subscription credentials. If you set `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in the sandbox environment, it doesn’t override your subscription credentials. + +#### + +​ + +Anthropic profiles and federation credentials + +A profile is a named credential configuration file in your [Anthropic configuration directory](<https://platform.claude.com/docs/en/manage-claude/wif-reference#configuration-directory>), by default `~/.config/anthropic` on macOS and Linux or `%APPDATA%\Anthropic` on Windows. A profile’s auth mode is `oidc_federation` when you set it up for [Workload Identity Federation (WIF)](<https://platform.claude.com/docs/en/manage-claude/workload-identity-federation>) or `user_oauth` when [`ant auth login`](<https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication>) wrote it. Claude Code doesn’t read profiles or federation variables in [bare mode](</docs/en/headless#start-faster-with-bare-mode>), in Claude Desktop, or in cloud sessions. Claude Code checks three sources in this order and stops at the first one that is set. The table shows what sets each source and where it ranks against your `/login` credential. + +Source| Set by| Rank against `/login` +---|---|--- +Named profile| `ANTHROPIC_PROFILE`| Above, whichever auth mode the profile has +Federation variables| `ANTHROPIC_FEDERATION_RULE_ID` and `ANTHROPIC_ORGANIZATION_ID`, both set| Above +Active profile| The [`active_config` file](<https://platform.claude.com/docs/en/manage-claude/wif-reference#active-profile>) in your configuration directory, or a profile named `default`| Above when its auth mode is `oidc_federation`; below a working `/login` credential when its auth mode is `user_oauth` + +The `user_oauth` rule keeps a leftover `ant auth login` profile from moving your requests off the account you signed in to with `/login`. For the federation variables, Claude Code also reads the other variables in the [WIF reference](<https://platform.claude.com/docs/en/manage-claude/wif-reference#environment-variables>), such as `ANTHROPIC_IDENTITY_TOKEN_FILE`, when it exchanges your identity token. For the profile file format, see the [WIF reference](<https://platform.claude.com/docs/en/manage-claude/wif-reference#profile-configuration-file>). To confirm which source Claude Code chose, run `/status`: a `Profile` row names the source in place of the `Login method` row. If you start Claude Code with `--debug`, it also writes a `Using Anthropic profile auth` line with the source name to the debug log at `~/.claude/debug/<session-id>.txt`. When Claude Code passes over a `user_oauth` active profile because you have a working `/login` credential, it writes a warning to the debug log saying it’s using the claude.ai login instead. When a `user_oauth` profile’s login has expired and Claude Code can’t renew it, requests fail with [Anthropic profile login expired](</docs/en/errors#anthropic-profile-login-expired>). Features that need your claude.ai login, such as [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) and [`/schedule`](</docs/en/routines>), aren’t available while one of these sources is selected. To stop Claude Code from selecting a source: + + * **Named profile or federation variables** : unset `ANTHROPIC_PROFILE`, or unset either federation variable + * **Active profile** : run `ant auth logout` for a `user_oauth` profile, or delete the profile’s file from `configs/` in your configuration directory for either auth mode ###
modified Configure auto mode View current →
--- a/auto-mode-config.md +++ b/auto-mode-config.md @@ -245,7 +245,7 @@ claude auto-mode critique -Run `claude auto-mode config` after saving your settings to confirm the effective rules are what you expect, with `"$defaults"` expanded in place. If you’ve written custom rules, `claude auto-mode critique` reviews them and flags entries that are ambiguous, redundant, or likely to cause false positives. If you need to remove or rewrite a built-in rule rather than add alongside it, save the output of `claude auto-mode defaults` to a file, edit the lists, and paste the result into your settings file in place of `"$defaults"`. To discard your customizations and return to the built-in defaults, run the reset subcommand. It requires Claude Code v2.1.212 or later and removes the `autoMode` section from your user settings file: +Run `claude auto-mode config` after saving your settings to confirm the effective rules are what you expect, with `"$defaults"` expanded in place. If you’ve written custom rules, `claude auto-mode critique` reviews them and flags entries that are ambiguous, redundant, or likely to cause false positives. To discard your customizations and return to the built-in defaults, run the reset subcommand. It requires Claude Code v2.1.212 or later and removes the `autoMode` section from your user settings file: claude auto-mode reset @@ -257,7 +257,7 @@ Review denials -When auto mode denies a tool call, Claude Code records the denial in `/permissions` under the **Recently denied** tab. Press `r` on a denied action to mark it for retry: when you exit the dialog, Claude Code sends a message telling the model it may retry that tool call and resumes the conversation. +To review and retry actions the auto mode classifier denied, open `/permissions` and select the **Recently denied** tab, where Claude Code records each denial. Press `r` on a denied action to mark it for retry: when you exit the dialog, Claude Code sends a message telling the model it may retry that tool call and resumes the conversation. When the classifier produces [no verdict on the action](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>), because a safety check separate from auto mode refused the classifier’s own request or its response didn’t parse, Claude Code denies the action without recording it under **Recently denied**. The linked error entry covers what Claude is told and how to run the action if you need it. ###
modified Best practices for Claude Code View current →
--- a/best-practices.md +++ b/best-practices.md @@ -403,7 +403,7 @@ * For more control, run `/compact <instructions>`, like `/compact Focus on the API changes` * To compact only part of the conversation, use `Esc + Esc` or `/rewind`, select a message checkpoint, and choose **Summarize from here** or **Summarize up to here**. The first condenses messages from that point forward while keeping earlier context intact; the second condenses earlier messages while keeping recent ones in full. See [the rewind menu’s summarize options](</docs/en/checkpointing#rewind-and-summarize>). * Customize compaction behavior in CLAUDE.md with instructions like `"When compacting, always preserve the full list of modified files and any test commands"` to ensure critical context survives summarization - * For quick questions that don’t need to stay in context, use [`/btw`](</docs/en/interactive-mode#side-questions-with-%2Fbtw>). The answer appears in a dismissible overlay and never enters conversation history, so you can check a detail without growing context. + * For questions that don’t need to stay in context, use [`/btw`](</docs/en/interactive-mode#side-questions-with-%2Fbtw>). The answer never enters conversation history, so you can check a detail without growing context. ###
modified Champion kit View current →
--- a/champion-kit.md +++ b/champion-kit.md @@ -1,4 +1,4 @@ -This page is for individual engineers who are already using Claude Code and want to help their team adopt it. It covers what to share, how to answer the questions you will get, a thirty-day playbook, and responses to common concerns. Adoption of a developer tool rarely happens because of a rollout announcement. It happens because someone on the team begins using the tool well, talks about it openly, and makes it easy for others to follow. The work you do as a champion has a disproportionate effect: every example you share shortens the learning curve for the engineers who come after you, and every question you answer in public turns one person’s experience into something the whole team can build on. You are acting as a multiplier for your team, not a help desk, and this guide is structured to keep the role sustainable on those terms. +This page is for individual engineers who are already using Claude Code and want to help their team adopt it. It covers what to share, how to answer the questions you will get, a thirty-day playbook, and responses to common concerns. Adoption of a developer tool rarely happens because of a rollout announcement. It happens because someone on the team begins using the tool well, talks about it openly, and makes it easy for others to follow. The work you do as a champion has a disproportionate effect: every example you share shortens the learning curve for the engineers who come after you, and every question you answer in public turns one person’s experience into something the whole team can build on. ## @@ -13,8 +13,6 @@ Share what you discover| Post the prompts, screenshots, and small wins from your own work in the places your team already reads, such as an engineering channel, a standup thread, or a pull-request description.| Examples drawn from your own codebase are more persuasive than any external documentation, because colleagues can see exactly how the tool applies to the problems they share with you. Be the person people ask| When a colleague asks how you accomplished something, respond with the actual prompt you used so they can apply it directly to their own task.| A concrete, runnable example removes the gap between curiosity and a first successful use, which is where most adoption efforts stall. Grow the circle| Establish a small number of lightweight, recurring habits, such as a dedicated channel or a weekly thread, so that momentum continues even when your attention is elsewhere.| Adoption that depends on a single person is fragile. Adoption that is carried by shared habits continues to compound on its own. - -Most of this fits naturally inside the work you are already doing. The difference is a small amount of additional intention about where your discoveries are posted and how your answers travel. ###
modified Claude Code changelog View current →
--- a/changelog.md +++ b/changelog.md @@ -1,4 +1,29 @@ 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.228 + +August 11, 2026 + + * Fixed interactive sessions that could stop redrawing entirely, while the process kept running, after a rare internal layout error + * Fixed `git` / Git Bash not being found on Windows when Claude Code is launched from a parent folder of the git installation + * Fixed `/tui` reverting the session to an earlier model when `/model` had been changed since the last response + * Fixed cross-session messaging sometimes starting without an inbox in the first session after install or upgrade + * Fixed Remote Control `/resume` while connected leaking the resumed conversation’s title or history into the connected session + * Fixed `claude self-hosted-runner` sessions failing on every fresh runner when the `checkout` hook fails for a repository the session doesn’t push to; that repository is now skipped with a warning + * Fixed self-hosted runners ending sessions in the gap between a background task finishing and the follow-up turn starting + * Fixed session cleanup deleting contents inside a project’s memory folder + * Fixed background plugin-cache cleanup deleting a plugin’s cache when its only version is a symlinked development checkout + * Fixed a settings-merge issue where a marketplace entry redefined in a higher-precedence settings tier could inherit another tier’s custom headers; marketplace entries now merge as whole entries + * Fixed the deferred-tools reminder occasionally being sent to the model twice after a skill invocation + * Hardened skills synced from claude.ai: they no longer shadow local commands or MCP prompts, their descriptions are sanitized and labeled, and on your machine their bodies don’t run `!` commands or expand `@` files + * Improved cross-session messages: the sender and body now display inline instead of a collapsed line, and messages to Remote Control sessions on other machines show your Remote Control session name as the sender + * Improved Vertex AI credential handling: expired or missing Google Cloud credentials now fail within seconds instead of retrying for minutes + * Improved compaction progress: the retry countdown and stall hint now appear during compaction instead of only a progress bar + * Updated terminal title busy-spinner glyphs to reduce tab-bar jitter on some terminals + * Changed the Write tool so newer models can overwrite an existing file they haven’t read this session, matching the Edit tool’s rules; older models still require the read first + * Removed the outdated note about auto mode sessions costing slightly more from the first-use notice for Pro, Max, and Team plans ​
modified Checkpointing View current →
--- a/checkpointing.md +++ b/checkpointing.md @@ -19,7 +19,7 @@ * Every user prompt creates a new checkpoint * Claude Code keeps file snapshots for the 100 most recent checkpoints in a session. Discarding an older checkpoint deletes the snapshot files that no remaining checkpoint references, except each file’s first snapshot, which the VS Code extension uses as the baseline for its session diffs. * Claude Code saves checkpoints with the conversation, so you can still run `/rewind` after you resume a session - * Claude Code deletes checkpoints along with sessions after 30 days; change the period with [`cleanupPeriodDays`](</docs/en/settings#available-settings>) + * Claude Code deletes checkpoints along with sessions after 30 days, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>); change the period with [`cleanupPeriodDays`](</docs/en/settings#available-settings>) ###
modified Use Claude Code with Chrome View current →
--- a/chrome.md +++ b/chrome.md @@ -63,7 +63,7 @@ Before Claude’s first browser action, Claude Code asks for permission to use the `claude-in-chrome` skill. Approve it and 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 when a browser action starts, Claude prompts you to pick one. 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. 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>). ### @@ -71,11 +71,11 @@ Install the extension when Claude asks -When Claude needs your browser for a task in an interactive session and Claude Code doesn’t detect the extension, Claude Code shows an install prompt titled “Claude wants to use your browser”, at most once per session. The prompt requires Claude Code v2.1.206 or later. On Windows, the **Install extension** choice requires v2.1.211 or later; before v2.1.211, choosing it couldn’t open the install page. The prompt offers three choices: - - * **Install extension** : opens the extension install page in your browser and starts a guided setup. Claude Code waits for the install, connects the extension, and enables browser tools in the same session. When the connection is ready, select “Continue with browser tools” and Claude resumes the task in your browser. You can leave setup at any point by selecting “Continue without browser tools” and finish later with `/chrome`. - * **Not now** : continues the task without browser tools. The prompt can appear again in a later session. - * **Don’t ask again** : stops the prompt in all future sessions. You can still set up the integration anytime with `/chrome`. +When Claude needs your browser in an interactive session and Claude Code doesn’t detect the extension, Claude Code shows an install prompt titled “Claude wants to use your browser”. Claude Code asks at most once per session. The prompt offers three choices: + + * **Install extension** : opens the extension install page in your browser and starts a guided setup. Claude Code waits for the install, connects the extension, and enables browser tools in the same session. When the connection is ready, select “Continue with browser tools” and Claude resumes the task in your browser. You can leave setup by selecting “Continue without browser tools” and finish later with `/chrome`. + * **Not now** : continues the task without browser tools. Claude Code can ask again in a later session. + * **Don’t ask again** : stops the prompt in future sessions. You can still set up the integration anytime with `/chrome`. If your organization blocks the `claude-in-chrome` MCP server with the [`deniedMcpServers` managed setting](</docs/en/managed-mcp#policy-based-control-with-allowlists-and-denylists>), Claude Code doesn’t show the install prompt. @@ -108,7 +108,7 @@ * **Read-only calls** : `read_page`, `get_page_text`, `find`, reading console messages or network requests, and taking a screenshot * **State-changing calls** : clicks, typing, navigation, tab and window management, and recording a GIF -As of v2.1.199, an otherwise read-only call that sets a state-changing input flag, such as `createIfEmpty` on `tabs_context_mcp`, `clear` on the console and network readers, or `save_to_disk` on a screenshot, also prompts for approval. A `browser_batch` call runs without a prompt only when every action inside it is read-only. +An otherwise read-only call also prompts for approval when it sets a state-changing input flag, such as `createIfEmpty` on `tabs_context_mcp`, `clear` on the console and network readers, or `save_to_disk` on a screenshot. A `browser_batch` call runs without a prompt only when every action inside it is read-only. ## @@ -261,7 +261,7 @@ 4. Run `/chrome` and select “Reconnect extension” to re-establish the connection 5. If the issue persists, restart both Claude Code and Chrome -The first time you enable Chrome integration, Claude Code installs a native messaging host configuration file. Chrome reads this file on startup, so if the extension isn’t detected on your first attempt, restart Chrome to pick up the new configuration. As of v2.1.199, Claude Code opens a browser tab prompting you to connect the extension only on that first install. Later sessions that rewrite the configuration file, for example after switching Claude Code builds or config directories, don’t reopen it. If the connection still fails, verify the host configuration file exists at: For Chrome: +The first time you enable Chrome integration, Claude Code installs a native messaging host configuration file. Chrome reads this file on startup, so if the extension isn’t detected on your first attempt, restart Chrome to pick up the new configuration. Claude Code opens a browser tab prompting you to connect the extension only on that first install. Claude Code doesn’t reopen it when a later session rewrites the configuration file, for example after switching builds or config directories. If the connection still fails, verify the host configuration file exists at: For Chrome: * **macOS** : `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json` * **Linux** : `~/.config/google-chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`
modified Claude apps gateway for Amazon Bedrock, Claude Platform on AWS, Google Cloud, and Microsoft Foundry View current →
--- a/claude-apps-gateway.md +++ b/claude-apps-gateway.md @@ -378,7 +378,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** : 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>). 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`, and any earlier claude.ai login are ignored while signed in, so developers don’t need to log out of claude.ai first. + * **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. * **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 @@ -18,6 +18,7 @@ * `admin`: Admin API auth and retention for spend limits * `enforcement`: spend-limit fail-open or fail-closed behavior + * `pricing`: contracted rates and a discount multiplier for the spend meter * `models` and `auto_include_builtin_models`: admin-curated model list and per-upstream IDs * `managed`: managed settings policies by IdP group * `telemetry`: OTLP forwarding to your observability stack @@ -379,7 +380,7 @@ `write_keys`| No| Array of `{id, key}`. An `x-api-key` matching one of these can list, set, and delete spend limits. Key values must be at least 32 characters; `id`s must be unique across `read_keys` and `write_keys`. `read_keys`| No| Array of `{id, key}`. Read-only: every `GET` endpoint, including listing caps, fetching one by ID, and reading [`/effective`](</docs/en/claude-apps-gateway-spend-limits#%2Feffective>) and [`/audit`](</docs/en/claude-apps-gateway-spend-limits#%2Faudit>). `admin_groups`| No| IdP group names. A gateway JWT whose `groups` claim includes one of these has full admin access, read and write, and audits as `oidc:<sub>`. Use this for human admins; use API keys for machines. -`blocked_message`| No| Appended verbatim to the `429 billing_error` a blocked developer sees. Write the whole instruction, such as a URL or a Slack channel. Unset, the error is `spend limit reached`. +`blocked_message`| No| Appended verbatim to the `429 billing_error` a blocked developer sees. Write the whole instruction, such as a URL or a Slack channel. When unset, the gateway sends only the default message. See [How enforcement works](</docs/en/claude-apps-gateway-spend-limits#how-enforcement-works>). `audit_retention_days`| No| Default `365`. Older `admin_audit` rows are swept. `spend_retention_months`| No| Default `13`. `spend` counter rows older than this are swept. The default keeps a full year plus the current partial month for year-over-year reporting. `identity_retention_days`| No| Default `90`. Last-seen TTL for `principal_emails` rows, which hold each developer’s email, display name, and groups (PII). Deliberately shorter than spend retention so a deprovisioned identity ages out while its anonymous spend counters remain. @@ -396,6 +397,42 @@ Field| Required| Description ---|---|--- `fail_closed_on_error`| No| Default `false`. Spend enforcement fails open on a Postgres outage, so inference stays up. Set `true` to fail closed: over-cap developers are blocked, but so is everyone else if the store is unreachable. Requires an `admin:` block: spend enforcement only runs when `admin` is configured, and the gateway refuses to start if you set this `true` without one. + +### + +​ + +`pricing` + +The `pricing` block tells the spend meter what to charge instead of USD list price, so caps and [`/effective`](</docs/en/claude-apps-gateway-spend-limits#%2Feffective>) reflect your contracted rates. Amounts stay in USD and remain an estimate, not an invoice. Two prerequisites: + + * Claude Code v2.1.227 or later on the gateway server. Earlier versions reject the unknown key at boot. + * An `admin:` block, because only the spend meter reads `pricing`. The gateway refuses to start with `pricing` set and no `admin`. + + pricing: + multiplier: 0.85 + overrides: + - upstream: bedrock-eu + model: claude-sonnet-4-6 + input: 3.30 + output: 16.50 + cache_read: 0.33 + cache_write: 4.125 + +Field| Required| Description +---|---|--- +`multiplier`| No| Default `1`. The meter multiplies every metered amount by this, whether list-priced or overridden, so `0.85` bills 85% of the price. Must be greater than 0 and at most 1. +`overrides`| No| Rows of `{upstream, model, input, output, cache_read, cache_write}` in USD per million tokens. All four rates are required and must be positive. + +How the meter matches an override row: + + * A row replaces list price for requests that `upstream`, an `upstreams[].name`, serves for `model`. That includes the higher [fast mode](</docs/en/fast-mode#understand-the-cost-tradeoff>) rate, so fast and standard requests meter at the same four rates. + * A built-in ID such as `claude-sonnet-4-6`, matched like `models[].id`, covers every dated form, regional Amazon Bedrock form, or Google Cloud’s Agent Platform form the meter prices as that model. Any other string, such as an alias or an inference-profile ARN, matches the ID the client sent or the string sent upstream, case-insensitively. + * Where rows overlap, the meter picks the most specific row rather than the first row: a row whose `model` is the exact model string sent upstream, then a row matching the exact ID the client sent, then a row naming the built-in model. + * An unknown upstream name fails boot, and so do two rows for one upstream that name the same model, including two spellings of one built-in model. The gateway warns at boot about a row no requestable model can use. + * Web-search requests stay at the $0.01 list price; the multiplier still applies to them. + +For per-region rates, give each region its own named upstream and one row per upstream. ### @@ -506,14 +543,14 @@ `env`| CLI| Environment variables merged into the CLI process. Use for telemetry, auto-update, and model-name overrides. `hooks`| CLI| Org-wide [hooks](</docs/en/hooks>) -Because these settings arrive over the network, the CLI shows each developer a one-time security approval dialog before applying the settings listed below: +Because these settings arrive over the network, the CLI shows each developer a security approval dialog before applying the settings listed below: * `hooks` * `env` variables that require the developer’s approval, such as proxy and base-URL variables * shell-execution settings such as `apiKeyHelper` and `statusLine` * managed CLAUDE.md content -Claude Code applies some delivered `env` variables without showing the developer the approval dialog, such as model selection settings and numeric limits. Other delivered variables can require the developer’s approval before they take effect; a non-empty proxy, base-URL, or `OTEL_EXPORTER_OTLP_ENDPOINT` value always does. When a delivered variable needs approval, the dialog names it. [Environment variables and the approval dialog](</docs/en/server-managed-settings#environment-variables-and-the-approval-dialog>) has the details, including four privacy toggles whose delivered value decides whether they need approval. Before v2.1.218, Claude Code applied fewer variables without asking the developer, so more delivered variables triggered the dialog. The gateway’s telemetry configuration pushes `OTEL_EXPORTER_OTLP_ENDPOINT`, so setting `telemetry.forward_to` triggers the dialog on each interactive client. The dialog protects the developer’s machine from a compromised or hostile gateway, not the organization from the developer. A non-interactive run with the `-p` flag can’t show the dialog. It applies the pushed settings for that run only and doesn’t record them as approved, so the developer’s next interactive session still shows the dialog. Before v2.1.207, a non-interactive run saved the settings as approved and no later interactive session showed the dialog for them. If a developer declines, Claude Code exits rather than applying the policy. Pushing a new hook, or any env var that triggers the dialog, to a broad policy therefore means an approval prompt on every matching developer’s next startup. The `cli` key was named `settings` in earlier releases. That spelling is still accepted as an alias, but new deployments should use `cli`. +[Approval memory](</docs/en/server-managed-settings#approval-memory>) covers how long an approval lasts and when the dialog appears again. Claude Code applies some delivered `env` variables without showing the developer the approval dialog, such as model selection settings and numeric limits. Other delivered variables can require the developer’s approval before they take effect; a non-empty proxy, base-URL, or `OTEL_EXPORTER_OTLP_ENDPOINT` value always does. When a delivered variable needs approval, the dialog names it. [Environment variables and the approval dialog](</docs/en/server-managed-settings#environment-variables-and-the-approval-dialog>) has the details, including four privacy toggles whose delivered value decides whether they need approval. Before v2.1.218, Claude Code applied fewer variables without asking the developer, so more delivered variables triggered the dialog. The gateway’s telemetry configuration pushes `OTEL_EXPORTER_OTLP_ENDPOINT`, so setting `telemetry.forward_to` triggers the dialog on each interactive client. The dialog protects the developer’s machine from a compromised or hostile gateway, not the organization from the developer. A non-interactive run with the `-p` flag can’t show the dialog. It applies the pushed settings for that run only and doesn’t record them as approved, so the developer’s next interactive session still shows the dialog. Before v2.1.207, a non-interactive run saved the settings as approved and no later interactive session showed the dialog for them. If a developer declines, Claude Code exits rather than applying the policy. Pushing a new hook, or any env var that triggers the dialog, to a broad policy therefore means an approval prompt on every matching developer’s next startup. The `cli` key was named `settings` in earlier releases. That spelling is still accepted as an alias, but new deployments should use `cli`. #### @@ -726,6 +763,13 @@ # enforcement: # fail_closed_on_error: false + + # Meter at contracted rates instead of USD list price. Requires admin:. + # Rates below are placeholders, not real contract prices. + # pricing: + # multiplier: 0.85 + # overrides: + # - { upstream: anthropic, model: claude-sonnet-4-6, input: 3.30, output: 16.50, cache_read: 0.33, cache_write: 4.125 } upstreams: - provider: anthropic
modified Claude apps gateway deployment and operations View current →
--- a/claude-apps-gateway-deploy.md +++ b/claude-apps-gateway-deploy.md @@ -226,7 +226,7 @@ If you add your own egress controls, the gateway must reach the metadata server whenever it uses instance-metadata credentials such as workload identity. Two threats are out of scope because they are your infrastructure to secure: - * **A compromised gateway host** : the host both holds the upstream credential and distributes [managed settings](</docs/en/claude-apps-gateway-config#managed>) to every connected developer, so control over the gateway’s configuration is comparable to control over your MDM. The CLI’s one-time approval dialog for shell-capable settings limits silent changes but doesn’t replace host security. + * **A compromised gateway host** : the host both holds the upstream credential and distributes [managed settings](</docs/en/claude-apps-gateway-config#managed>) to every connected developer, so control over the gateway’s configuration is comparable to control over your MDM. The CLI’s [approval dialog](</docs/en/server-managed-settings#approval-memory>) for shell-capable settings limits silent changes but doesn’t replace host security. * **A malicious OIDC provider** : the provider signs the id_tokens the gateway trusts, so it can assert any identity. Vetting and securing your IdP is your responsibility. ###
modified Deploy Claude apps gateway on AWS View current →
--- a/claude-apps-gateway-on-aws.md +++ b/claude-apps-gateway-on-aws.md @@ -450,7 +450,7 @@ Telemetry -The gateway gives you per-developer usage metrics without any per-machine OTEL configuration. Claude Code emits OpenTelemetry (OTLP) metrics, logs, and opt-in traces; [Monitoring usage](</docs/en/monitoring-usage>) covers everything the CLI reports. On gateway sessions the CLI stamps each export with the authenticated IdP identity attributes `user.id`, `user.email`, and `user.groups`, so usage rolls up per developer with no `OTEL_RESOURCE_ATTRIBUTES` plumbing. The gateway itself is an authenticated OTLP relay. Set [`telemetry.forward_to`](</docs/en/claude-apps-gateway-config#telemetry>) together with `listen.public_url`, and it pushes the OTEL exporter settings to every connected client and forwards their OTLP traffic verbatim to each destination you list. Each destination opts into metrics, logs, and traces independently, and the default is metrics only; see the [`telemetry` reference](</docs/en/claude-apps-gateway-config#telemetry>) for the per-signal fields and their sensitivity tradeoffs. The gateway doesn’t buffer, aggregate, or store telemetry, so where the data lands is entirely the collector’s exporter configuration. Client telemetry is off by default; configuring `telemetry.forward_to` is what turns it on for connected developers, and each interactive client shows a one-time security approval dialog for the pushed settings, as described in the [configuration reference](</docs/en/claude-apps-gateway-config#telemetry>). On AWS, each signal maps to a destination as follows. +The gateway gives you per-developer usage metrics without any per-machine OTEL configuration. Claude Code emits OpenTelemetry (OTLP) metrics, logs, and opt-in traces; [Monitoring usage](</docs/en/monitoring-usage>) covers everything the CLI reports. On gateway sessions the CLI stamps each export with the authenticated IdP identity attributes `user.id`, `user.email`, and `user.groups`, so usage rolls up per developer with no `OTEL_RESOURCE_ATTRIBUTES` plumbing. The gateway itself is an authenticated OTLP relay. Set [`telemetry.forward_to`](</docs/en/claude-apps-gateway-config#telemetry>) together with `listen.public_url`, and it pushes the OTEL exporter settings to every connected client and forwards their OTLP traffic verbatim to each destination you list. Each destination opts into metrics, logs, and traces independently, and the default is metrics only; see the [`telemetry` reference](</docs/en/claude-apps-gateway-config#telemetry>) for the per-signal fields and their sensitivity tradeoffs. The gateway doesn’t buffer, aggregate, or store telemetry, so where the data lands is entirely the collector’s exporter configuration. Client telemetry is off by default; configuring `telemetry.forward_to` is what turns it on for connected developers, and each interactive client shows a security approval dialog for the pushed settings, as described in the [configuration reference](</docs/en/claude-apps-gateway-config#telemetry>). On AWS, each signal maps to a destination as follows. ###
modified Claude apps gateway spend limits View current →
--- a/claude-apps-gateway-spend-limits.md +++ b/claude-apps-gateway-spend-limits.md @@ -45,13 +45,22 @@ How enforcement works -On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly at 00:00 UTC on Monday, and monthly at 00:00 UTC on the first of the month. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. A running gateway serves a protocol description at `<public_url>/protocol` that lists the exact usage-limit response headers and the shape of the blocked `429`. Requires v2.1.227 or later. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Amazon Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms, such as Bedrock’s `us.anthropic.…-v1:0` and Agent Platform’s `claude-…@date`. The meter resolves each request’s rate tier in order: +On each `/v1/messages` request, the gateway looks up the developer’s caps and period-to-date spend in one Postgres query. A developer over any cap gets a `429` with `error.type: billing_error` and header `x-should-retry: false`. The message names the period and reset time, such as `spend limit reached (daily; resets 2026-08-08 00:00 UTC)`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. When a developer exceeds several caps at once, the message names the cap that resets last. The response also carries a `retry-after` header with the seconds remaining until that reset. Before v2.1.225 on the gateway server, the message was `spend limit reached` with no period, reset time, or `retry-after` header. On v2.1.227 or later, the protocol reference at `<public_url>/protocol` also lists the exact usage-limit response headers and `429` body. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly on Monday, and monthly on the first. The gateway never blocks `/v1/messages/count_tokens`, because token counting is free. - 1. Exact rates for the upstream model ID, the model string the gateway sends to the provider. When the table recognizes it, such as `us.anthropic.claude-…`, the meter prices the request by the model that served it. - 2. Rates for the configured [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to the upstream ID. This step covers upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name, and requires Claude Code v2.1.218 or later on the gateway server. - 3. The unknown-model default tier of $5/$25 per million input/output tokens. The meter prices an ID that neither the table nor your `models` config can place, including a `models[].id` that is itself a custom alias, at this tier rather than zero, so an unrecognized ID can’t bypass a cap by going unmetered. +### -The gateway warns at boot and once per ID at runtime when it prices a model at the unknown-model tier. Before v2.1.218, the meter skipped step 2: it priced any upstream ID the table couldn’t place at the unknown-model tier and warned about it even when the configured ID’s rates were known. Client aborts are billed too. The upstream reports output tokens only in the stream’s terminal frame, so an aborted stream doesn’t carry them. The meter keeps a conservative floor estimate from the streamed content size, about four characters per token, and bills it when and only when the terminal usage frame is missing. A complete stream always bills the upstream-reported count. Without this, a capped developer could stream output and abort each request immediately before the end, spending without ever being counted. +​ + +How requests are priced + +After each response, a usage meter reads the token counts and adds the cost to the daily, weekly, and monthly counters. It never touches the bytes sent to the client, so a metering failure can’t break a response. The amounts are USD estimates, a circuit breaker rather than an invoice; for billing, reconcile against your provider’s usage reporting. The meter picks each request’s rates in this order: + + 1. A matching [`pricing.overrides`](</docs/en/claude-apps-gateway-config#pricing>) row for the upstream that served the request. Requires v2.1.227 or later. + 2. List price for the upstream model ID, the string the gateway sends to the provider, when the Claude Code cost table recognizes it. The table accepts Anthropic, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms. + 3. List price for the [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to that upstream ID, for upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name. Requires v2.1.218 or later. + 4. The unknown-model tier of $5/$25 per million input/output tokens, so an ID the meter can’t place is never free. The gateway warns at boot and once per ID at runtime when it uses this tier. + +Whichever rate applies, the meter then multiplies the amount by [`pricing.multiplier`](</docs/en/claude-apps-gateway-config#pricing>), default `1`. Client aborts are billed too. When a stream ends without the upstream’s final usage frame, the meter bills a floor estimate of about four characters per output token for the text already sent to the client, so aborting requests early doesn’t evade a cap. ### @@ -59,7 +68,20 @@ Postgres availability -The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds and the gateway logs a warning. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` with the message `spend limit unavailable`. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend. +The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds, the gateway logs a warning, and the response carries no `anthropic-ratelimit-unified-*` headers. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` but with the message `spend limit unavailable` and no period, reset time, or `retry-after` header. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend. + +### + +​ + +Usage warnings in Claude Code + +Claude Code warns a developer as they approach their cap: once utilization passes 75%, and again past 95% of their fullest cap. When the gateway blocks a request, Claude Code shows the gateway’s `429` message as is, including your `admin.blocked_message`. The warning works off response headers: + + * With v2.1.225 or later on the gateway server, each successful `/v1/messages` response for a developer who has a cap carries their own cap utilization and reset time in the `anthropic-ratelimit-unified-*` headers. + * With v2.1.225 or later on the developer’s machine as well, Claude Code reads the headers and shows the warning. + +The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them. ##
modified Use Claude Code on the web View current →
--- a/claude-code-on-the-web.md +++ b/claude-code-on-the-web.md @@ -61,7 +61,7 @@ claude --cloud "Fix the authentication bug in src/auth/login.ts" -This creates a new cloud session on claude.ai. The session clones your current directory’s GitHub remote at your current branch, so push first if you have local commits, since the VM clones from GitHub rather than your machine. `--cloud` works with a single repository at a time. The task runs in the cloud while you continue working locally. The older `--remote` spelling still works as a deprecated alias for `--cloud`. As of v2.1.195, the CLI shows a live checklist of setup steps, such as cloning the repository and running your [setup script](</docs/en/cloud-environments#setup-scripts>), while the cloud container starts. Messages you type while the container is provisioning are queued and sent once the session is ready. +This creates a new cloud session on claude.ai. The cloud VM clones your current directory’s GitHub remote at your current branch, not your local checkout, so push first if you have local commits. `--cloud` works with a single repository at a time. The task runs in the cloud while you continue working locally. The older `--remote` spelling still works as a deprecated alias for `--cloud`. While the cloud container starts, the CLI shows a live checklist of setup steps, such as cloning the repository and running your [setup script](</docs/en/cloud-environments#setup-scripts>). It queues messages you type during provisioning and sends them once the session is ready. `--cloud` creates cloud sessions. `--remote-control` is unrelated: it exposes a local CLI session for monitoring from the web. See [Remote Control](</docs/en/remote-control>). @@ -208,7 +208,7 @@ `/context`| Yes| Shows what’s currently in the context window `/clear`| No| Start a new session from the sidebar instead -Auto-compaction runs automatically when the context window approaches capacity. To trigger it earlier, set [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](</docs/en/env-vars>) in your [environment variables](</docs/en/cloud-environments#set-environment-variables>). For example, `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70` compacts at 70% capacity instead of waiting until the window is nearly full. The percentage moves compaction earlier within the [auto-compact window](</docs/en/context-window#set-the-auto-compact-window>). To change the window itself, set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>), 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 Task 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>). +Auto-compaction runs automatically when the context window approaches capacity. To trigger it earlier, set [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](</docs/en/env-vars>) in your [environment variables](</docs/en/cloud-environments#set-environment-variables>). For example, `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70` compacts at 70% capacity instead of waiting until the window is nearly full. The percentage moves compaction earlier within the [auto-compact window](</docs/en/model-config#set-the-auto-compact-window>). To change the window itself, set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>), 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 Task 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>). ###
modified Explore the .claude directory View current →
--- a/claude-directory.md +++ b/claude-directory.md @@ -20,7 +20,7 @@ ---|---|--- `managed-settings.json`| System-level, varies by OS| Enterprise-enforced settings that you can’t override, apart from [narrow exceptions](</docs/en/settings#settings-precedence>). See [server-managed settings](</docs/en/server-managed-settings>). `CLAUDE.local.md`| Project root| Your private preferences for this project, loaded alongside CLAUDE.md. Create it manually and add it to `.gitignore`. -Installed plugins| `~/.claude/plugins`| Cloned marketplaces, installed plugin versions, and per-plugin data, managed by `claude plugin` commands. Orphaned versions are deleted 14 days after a plugin update or uninstall. See [plugin caching](</docs/en/plugins-reference#plugin-caching-and-file-resolution>). +Installed plugins| `~/.claude/plugins`| Cloned marketplaces, installed plugin versions, and per-plugin data, managed by `claude plugin` commands. See [plugin caching](</docs/en/plugins-reference#plugin-caching-and-file-resolution>) for how orphaned versions are cleaned up. `~/.claude` also holds data Claude Code writes as you work: transcripts, prompt history, file snapshots, caches, and logs. See application data below. @@ -104,7 +104,7 @@ Cleaned up automatically -Files in the paths below are deleted on startup once they’re older than [`cleanupPeriodDays`](</docs/en/settings#available-settings>). The default is 30 days and the minimum is 1; setting `0` fails with a validation error. The same age cutoff applies to automatic removal of [orphaned worktrees](</docs/en/worktrees#clean-up-subagent-and-background-session-worktrees>). +Claude Code deletes the files in the paths below once they’re older than [`cleanupPeriodDays`](</docs/en/settings#available-settings>), as long as it can safely determine the retention period. The default is 30 days and the minimum is 1; setting `0` fails with a validation error. The same age cutoff applies to automatic removal of [orphaned worktrees](</docs/en/worktrees#clean-up-subagent-and-background-session-worktrees>). Path under `~/.claude/`| Contents ---|--- @@ -120,9 +120,10 @@ `shell-snapshots/`| Aliases, functions, and shell options captured at startup and applied by the [Bash tool](</docs/en/tools-reference#bash-tool-behavior>) to each command. Removed on clean exit. The sweep clears any left after a crash. `backups/`| Timestamped copies of `~/.claude.json` taken before config migrations `feedback-bundles/`| Redacted transcript archives written by `/feedback` on third-party providers or when no Anthropic credentials are configured, for sending to your Anthropic account team +`usage-data/`| `report.html` and timestamped report copies written by [`/insights`](</docs/en/costs#analyze-your-usage-patterns>), plus cached per-session analysis data used to build them `todos/`, `statsig/`, `logs/`| Legacy directories from older versions. No longer written. The sweep removes their contents and then the empty directory. -`sessions/` holds one small file per running session, used to detect concurrent sessions and crashes. It isn’t part of the age-based sweep: Claude Code removes each file when its session exits and clears crash leftovers on the next launch. If Claude Code can’t read or parse a settings file, it pauses the retention cleanup sweep and shows a warning in `/status` until you fix the file, unless [managed settings](</docs/en/server-managed-settings>) provide `cleanupPeriodDays`, in which case the sweep runs at the managed value. Before v2.1.203, cleanup ran at the 30-day default in that state and could delete transcripts a longer `cleanupPeriodDays` was meant to keep; files newer than 30 days were never removed. +`sessions/` holds one small file per running session, used to detect concurrent sessions and crashes. It isn’t part of the age-based sweep: Claude Code removes each file when its session exits and clears crash leftovers on the next launch. When you run `claude -p` with [`--bare`](</docs/en/headless#start-faster-with-bare-mode>), Claude Code doesn’t run the sweep in that session. If Claude Code can’t safely determine the retention period, it pauses the retention cleanup sweep; the [`retention_sweep` event](</docs/en/monitoring-usage#retention-sweep-event>) lists each configuration that pauses it. When the cause is a settings file that can’t be read or parsed, or settings errors with `cleanupPeriodDays` explicitly set, Claude Code also shows a warning in `/status` until you fix the settings errors. When [managed settings](</docs/en/server-managed-settings>) provide `cleanupPeriodDays`, Claude Code runs the sweep at the managed value in either case. ### @@ -203,6 +204,8 @@ `~/.claude/paste-cache/`| Pasted text in recalled prompts; see [paste large content](</docs/en/terminal-config#paste-large-content>) `~/.claude/file-history/`| Checkpoint restore for past sessions `~/.claude/stats-cache.json`| Historical totals shown by `/usage` +`~/.claude/usage-data/`| Past [`/insights`](</docs/en/costs#analyze-your-usage-patterns>) reports and the cached analysis data used to build them +`~/.claude/feedback-bundles/`| Feedback and bug-report archives you haven’t yet sent to your Anthropic account team `~/.claude/remote-settings.json`| Nothing. Re-fetched on next launch. `~/.claude/cache/changelog.md`| Nothing. Refreshed in the background. `~/.claude/policy-limits.json`| Nothing. Refreshed automatically.
modified Claude Code on Claude Platform on AWS View current →
--- a/claude-platform-on-aws.md +++ b/claude-platform-on-aws.md @@ -38,13 +38,13 @@ "awsAuthRefresh": "aws sso login --profile my-profile" } -Claude Code also runs this command at startup when it can’t validate your existing AWS credentials, and shows the command’s output in an `Authentication` panel until the login completes. Before v2.1.212, the panel was titled `Cloud authentication`. With `awsAuthRefresh` configured, `/login` shows a **Claude Platform on AWS · refresh credentials** option under **Using 3rd-party platforms**. Selecting it runs the configured command and re-reads your AWS credentials without restarting Claude Code. **Option B: Workspace API key** A workspace API key is a long-lived secret, useful when you don’t want to manage federated AWS credentials. Generate one in the AWS Console under **Claude Platform on AWS → API keys** and set it as `ANTHROPIC_AWS_API_KEY`: +Claude Code also runs this command at startup when it can’t validate your existing AWS credentials, and shows the command’s output in an `Authentication` panel until the login completes. With `awsAuthRefresh` configured, `/login` shows a **Claude Platform on AWS · refresh credentials** option under **Using 3rd-party platforms**. Selecting it runs the configured command and re-reads your AWS credentials without restarting Claude Code. **Option B: Workspace API key** A workspace API key is a long-lived secret, useful when you don’t want to manage federated AWS credentials. Generate one in the AWS Console under **Claude Platform on AWS → API keys** and set it as `ANTHROPIC_AWS_API_KEY`: export ANTHROPIC_AWS_API_KEY=sk-ant-xxxxx The key is sent as `x-api-key` and takes precedence over SigV4, so any AWS credentials in your environment are ignored. API keys from a separate Claude Console organization won’t work here. Treat workspace API keys like any other production credential. The [user settings file](</docs/en/settings>) `env` block is a convenient way to scope the key to your machine without exporting it globally. -The `/login` and `/logout` commands don’t sign you into a Claude.ai subscription for Claude Platform on AWS. Authentication runs through your AWS credentials or workspace API key. The exception is the **refresh credentials** option `/login` shows when `awsAuthRefresh` is configured, which re-reads your AWS credentials as described above. +The `/login` and `/logout` commands don’t sign you into a Claude.ai subscription for Claude Platform on AWS. Authentication runs through your AWS credentials or workspace API key. ###
modified CLI reference View current →
--- a/cli-reference.md +++ b/cli-reference.md @@ -38,9 +38,10 @@ `claude remote-control`| Start a [Remote Control](</docs/en/remote-control>) server to control Claude Code from Claude.ai or the Claude app. Runs in server mode (no local interactive session). See [Server mode flags](</docs/en/remote-control#start-a-remote-control-session>)| `claude remote-control --name "My Project"` `claude respawn <id>`| Restart a [background session](</docs/en/agent-view#manage-sessions-from-the-shell>), running or stopped, with its conversation intact. Use `--all` to restart every running session, e.g. to pick up an updated Claude Code binary| `claude respawn 7c5dcf5d` `claude rm <id>`| Remove a [background session](</docs/en/agent-view#manage-sessions-from-the-shell>) from the list. The conversation transcript stays on your local machine, available through `claude --resume`| `claude rm 7c5dcf5d` +`claude self-hosted-runner`| Start a runner process that registers this machine or container with a [self-hosted environment](</docs/en/self-hosted-environments>) and hosts Claude Code cloud sessions on your infrastructure. Run `claude self-hosted-runner setup` for a guided operator walkthrough, `claude self-hosted-runner doctor` to [diagnose a deployed runner](</docs/en/self-hosted-environments-deploy#troubleshooting>), and `claude self-hosted-runner orchestrator` to spawn [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>). Requires Claude Code v2.1.224 or later| `claude self-hosted-runner setup` `claude setup-token`| Generate a long-lived OAuth token for CI and scripts. Prints the token to the terminal without saving it. Requires a Claude subscription. See [Generate a long-lived token](</docs/en/authentication#generate-a-long-lived-token>)| `claude setup-token` `claude stop <id>`| Stop a [background session](</docs/en/agent-view#manage-sessions-from-the-shell>). Also accepts `claude kill`| `claude stop 7c5dcf5d` -`claude ultrareview [target]`| Run [ultrareview](</docs/en/ultrareview#run-ultrareview-non-interactively>) non-interactively. Prints findings to stdout and exits 0 on success or 1 on failure. Use `--json` for the raw payload and `--timeout <minutes>` to override the 30-minute default| `claude ultrareview 1234 --json` +`claude ultrareview [target]`| Run [ultrareview](</docs/en/ultrareview#run-ultrareview-non-interactively>) non-interactively. Prints findings to stdout and exits 0 on success or 1 on failure. Use `--json` for the raw payload and `--timeout <minutes>` to override the 30-minute default. Use `--post` on a `github.com` pull request target to post the finished findings to the PR as one plain comment from your GitHub account. `--no-post` is the default. Requires Claude Code v2.1.227 or later. See [Post findings to the pull request](</docs/en/ultrareview#post-findings-to-the-pull-request>)| `claude ultrareview 1234 --json` If you mistype a subcommand, Claude Code suggests the closest match and exits without starting a session. For example, `claude udpate` prints `Did you mean claude update?`. As of v2.1.199, `claude --dangerously-skip-permissions daemon <subcommand>` runs the `daemon` subcommand. Earlier versions treated `daemon <subcommand>` as the prompt for a new interactive session, so the subcommand never ran when the flag came first, a common setup when `claude` is aliased to include the flag. Only a leading `--dangerously-skip-permissions` or `--allow-dangerously-skip-permissions` routes to `daemon` this way; any other leading flag still starts an interactive session. @@ -63,7 +64,7 @@ `--append-subagent-system-prompt`| Append custom text to the end of every [subagent](</docs/en/sub-agents>)’s system prompt, including nested subagents. Only applies in non-interactive mode with `-p`. Requires Claude Code v2.1.205 or later| `claude -p --append-subagent-system-prompt "Cite file paths in every answer" "query"` `--append-system-prompt`| Append custom text to the end of the default system prompt| `claude --append-system-prompt "Always use TypeScript"` `--append-system-prompt-file`| Load additional system prompt text from a file and append to the default prompt| `claude --append-system-prompt-file ./extra-rules.txt` -`--autocompact <auto|tokens>`| Set the [auto-compact window](</docs/en/context-window#set-the-auto-compact-window>) for this session without changing your saved settings. Accepts the same values as `/autocompact`; that section covers the value forms and what overrides the flag. Requires Claude Code v2.1.221 or later| `claude --autocompact 500k` +`--autocompact <auto|tokens>`| Set the [auto-compact window](</docs/en/model-config#set-the-auto-compact-window>) for this session without changing your saved settings. Accepts the same values as `/autocompact`; that section covers the value forms and what overrides the flag. Requires Claude Code v2.1.221 or later| `claude --autocompact 500k` `--ax-screen-reader`| Render screen-reader friendly output: flat text without decorative borders or animations. Forces the classic renderer, so the [`tui`](</docs/en/settings#available-settings>) setting has no effect; attached [background sessions](</docs/en/agent-view>) still render fullscreen. Takes precedence over [`CLAUDE_AX_SCREEN_READER`](</docs/en/env-vars>) and the [`axScreenReader`](</docs/en/settings#available-settings>) setting. Requires Claude Code v2.1.181 or later| `claude --ax-screen-reader` `--bare`| Minimal mode: skip auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md so scripted calls start faster. Claude has access to Bash, file read, and file edit tools. Sets [`CLAUDE_CODE_SIMPLE`](</docs/en/env-vars>). See [bare mode](</docs/en/headless#start-faster-with-bare-mode>)| `claude --bare -p "query"` `--betas`| Beta headers to include in API requests (API key users only)| `claude --betas interleaved-thinking` @@ -80,23 +81,23 @@ `--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#available-settings>) setting for this session and does not persist| `claude --effort high` `--enable-auto-mode`| Removed in v2.1.111. Auto mode is now in the `Shift+Tab` cycle by default; use `--permission-mode auto` to start in it| `claude --permission-mode auto` -`--environment <environment-id>`| With `-p`, create a new [cloud session](</docs/en/claude-code-on-the-web>) on the named environment and exit without waiting for a reply; self-hosted environment IDs have the form `ccpool_...`. Can’t be combined with `--cloud`. See [dispatch from a script](</docs/en/self-hosted-environments-testing#run-the-test-loop>)| `claude -p "Run the smoke test" --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 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` `--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#available-settings>), which this flag overrides| `claude --fallback-model sonnet,haiku` `--fork-session`| When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`)| `claude --resume abc123 --fork-session` -`--forward-subagent-text`| Emit [subagent](</docs/en/sub-agents>) text and thinking blocks in the output stream as `assistant` and `user` messages with `parent_tool_use_id` set, so you can reconstruct each subagent’s transcript. Without this flag, Claude Code emits only subagent `tool_use` and `tool_result` blocks. Requires `--print` and `--output-format stream-json`. The [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>) environment variable enables the same behavior. Requires Claude Code v2.1.211 or later| `claude -p --output-format stream-json --verbose --forward-subagent-text "query"` +`--forward-subagent-text`| Emit [subagent](</docs/en/sub-agents>) text and thinking blocks in the output stream as `assistant` and `user` messages with `parent_tool_use_id` set, so you can reconstruct each subagent’s transcript. Without this flag, Claude Code emits only subagent `tool_use` and `tool_result` blocks. Requires `--print` and `--output-format stream-json`. Claude Code also forwards messages from [nested subagents](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), setting `parent_tool_use_id` to the ID of the Agent tool call that spawned each one; this requires Claude Code v2.1.219 or later. The [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>) environment variable enables the same behavior. Requires Claude Code v2.1.211 or later| `claude -p --output-format stream-json --verbose --forward-subagent-text "query"` `--from-pr`| Open the session picker filtered to sessions linked to a specific pull request. Accepts a PR number, a GitHub or GitHub Enterprise PR URL, a GitLab merge request URL, or a Bitbucket pull request URL. Sessions are linked automatically when Claude creates the pull request| `claude --from-pr 123` `--ide`| Automatically connect to IDE on startup if exactly one valid IDE is available| `claude --ide` `--init`| Run [Setup hooks](</docs/en/hooks#setup>) with the `init` matcher before the session (print mode only)| `claude -p --init "query"` `--init-only`| Run [Setup](</docs/en/hooks#setup>) and `SessionStart` hooks, then exit without starting a conversation| `claude --init-only` -`--include-hook-events`| Include hook lifecycle events from every hook event in the output stream. `SessionStart` and `Setup` hook events are always included and don’t need this flag. Requires `--output-format stream-json`| `claude -p --output-format stream-json --verbose --include-hook-events "query"` +`--include-hook-events`| Include hook lifecycle events in the output stream. `SessionStart` and `Setup` hook events are always included and don’t need this flag. Some hook events, such as `Notification`, `SessionEnd`, `PreCompact`, and `PostCompact`, never produce a `hook_started` event, even with this flag. For those events, Claude Code still emits `hook_progress` while a command hook that runs for more than a second produces output, and emits `hook_response` only when a [hook that runs in the background](</docs/en/hooks#run-hooks-in-the-background>) finishes. Requires `--output-format stream-json`| `claude -p --output-format stream-json --verbose --include-hook-events "query"` `--include-partial-messages`| Include partial streaming events in output. Requires `--print` and `--output-format stream-json`| `claude -p --output-format stream-json --verbose --include-partial-messages "query"` `--input-format`| Specify input format for print mode (options: `text`, `stream-json`)| `claude -p --output-format json --input-format stream-json` -`--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. Before v2.1.205, an invalid schema produced unstructured output with no error, and schemas using `format` were treated as invalid| `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` +`--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. Before v2.1.205, Claude Code discarded that message| `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 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"` `--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#available-settings>) 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>`. @@ -106,7 +107,7 @@ `--no-session-persistence`| Disable session persistence so sessions are not saved to disk and cannot be resumed. Print mode only. The [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>) environment variable does the same in any mode| `claude -p --no-session-persistence "query"` `--output-format`| Specify output format for print mode (options: `text`, `json`, `stream-json`)| `claude -p "query" --output-format json` `--permission-mode`| Begin in a specified [permission mode](</docs/en/permission-modes>). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions`, or `manual` as an alias for `default`. The `manual` alias selects the mode the UI labels Manual and requires Claude Code v2.1.200 or later; `claude --help` lists it in place of `default`, and both values work. Overrides `defaultMode` from settings files| `claude --permission-mode plan` -`--permission-prompt-tool`| Specify an MCP tool to handle permission prompts in non-interactive mode. Claude Code waits for that tool’s MCP server to connect before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. Before v2.1.206, a slow-starting server could make the run [exit with an error that the MCP tool was not found](</docs/en/errors#mcp-permission-prompt-tool-not-found>). +`--permission-prompt-tool`| Specify an MCP tool to handle permission prompts in non-interactive mode. Claude Code waits for that tool’s MCP server to connect before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. The prompt tool can’t approve an MCP tool marked as [requiring user interaction](</docs/en/mcp#require-approval-for-a-specific-tool>): Claude Code converts an `allow` result for one to a deny. This restriction requires Claude Code v2.1.199 or later| `claude -p --permission-prompt-tool mcp_auth_tool "query"` `--plugin-dir`| Load a plugin from a directory or `.zip` archive for this session only. Each flag takes one path. Repeat the flag for multiple plugins: `--plugin-dir A --plugin-dir B.zip`| `claude --plugin-dir ./my-plugin` @@ -127,7 +128,7 @@ `--system-prompt`| Replace the entire system prompt with custom text| `claude --system-prompt "You are a Python expert"` `--system-prompt-file`| Load system prompt from a file, replacing the default prompt| `claude --system-prompt-file ./custom-prompt.txt` `--teleport`| Resume a [web session](</docs/en/claude-code-on-the-web>) in your local terminal| `claude --teleport` -`--teammate-mode`| Set how [agent team](</docs/en/agent-teams>) teammates display: `in-process` (default), `auto`, `tmux`, or `iterm2` (added in v2.1.186). The default changed from `auto` in v2.1.179. Overrides the [`teammateMode`](</docs/en/settings#available-settings>) setting for this session. See [Choose a display mode](</docs/en/agent-teams#choose-a-display-mode>)| `claude --teammate-mode auto` +`--teammate-mode`| Set how [agent team](</docs/en/agent-teams>) teammates display: `in-process` (default), `auto`, `tmux`, or `iterm2` (added in v2.1.186). Overrides the [`teammateMode`](</docs/en/settings#available-settings>) setting for this session. See [Choose a display mode](</docs/en/agent-teams#choose-a-display-mode>)| `claude --teammate-mode auto` `--tmux`| Create a tmux session for the worktree. Requires `--worktree`. Uses iTerm2 native panes when available; pass `--tmux=classic` for traditional tmux| `claude -w feature-auth --tmux` `--tools`| Restrict which built-in tools Claude can use. Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"`. The flag doesn’t affect MCP tools; to deny those too, use `--disallowedTools "mcp__*"`, or pass `--strict-mcp-config` without `--mcp-config` so no MCP servers load. A list that omits [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) doesn’t remove it; `""` removes it only when no MCP tools remain| `claude --tools "Bash,Edit,Read"` `--verbose`| Enable verbose logging, shows full turn-by-turn output. Overrides the [`viewMode`](</docs/en/settings#available-settings>) setting for this session| `claude --verbose`
modified Configure cloud environments View current →
--- a/cloud-environments.md +++ b/cloud-environments.md @@ -18,7 +18,7 @@ With only **Default** available, every session runs in it. When you have more than one environment, sessions choose one per surface: * On the web, the Desktop app, and the mobile app, sessions use the environment shown in the selector. An admin-set organization default fills the selection when you haven’t picked one. - * From the CLI, sessions use your `/remote-env` pick, or fall back to your first available cloud environment. Passing `--environment <environment-id>` on a [scripted dispatch](</docs/en/self-hosted-environments-testing#run-the-test-loop>) overrides both for that invocation; the flag requires Claude Code v2.1.224 or later. + * From the CLI, sessions use your `/remote-env` pick, or fall back to your first available cloud environment. For a [self-hosted environment](</docs/en/self-hosted-environments>), passing `--environment <environment-id>` with its `ccpool_` ID [when you dispatch a session](</docs/en/self-hosted-environments-testing#run-the-test-loop>) overrides both for that invocation. The flag rejects Anthropic-hosted `env_` IDs, so use `/remote-env` to target those. The flag requires Claude Code v2.1.224 or later. Configure an environment when the default isn’t enough: when Claude needs to reach domains outside the default allowlist, needs environment variables set for its sessions, or needs dependencies installed before it starts working.
modified Code Review View current →
--- a/code-review.md +++ b/code-review.md @@ -10,8 +10,6 @@ * Troubleshooting failed runs and missing comments * Reviewing a diff locally with the `/code-review` command -To review a diff locally in your terminal without installing the GitHub App, run the `/code-review` command in any Claude Code session. See Review a diff locally. - ## ​ @@ -240,7 +238,7 @@ Feedback| Count of review comments that were auto-resolved because a developer addressed the issue Repository breakdown| Per-repo counts of PRs reviewed and comments resolved -The repositories table in admin settings also shows average cost per review for each repo. Dashboard cost figures are estimates for monitoring activity; for invoice-accurate spend, refer to your Anthropic bill. +Dashboard cost figures are estimates for monitoring activity. For invoice-accurate spend, refer to your Anthropic bill. ## @@ -312,6 +310,7 @@ * `--fix`: applies the findings to your working tree after the review * `--comment`: posts the findings as inline PR comments + * `--post`: on an `ultra` cloud review of a `github.com` pull request, preselects posting the finished findings to the PR in the launch dialog; see [Post findings to the pull request](</docs/en/ultrareview#post-findings-to-the-pull-request>). Requires Claude Code v2.1.227 or later 2 @@ -363,7 +362,27 @@ * You run it in non-interactive mode, with the `-p` flag or the Agent SDK; Claude Code waits for the review and includes the findings in the response, except for `ultra`, which launches the cloud review without waiting * You set [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`](</docs/en/env-vars>) to `1`, which also turns off every other background task feature -You can’t schedule the review: `/code-review` is marked [`disable-model-invocation`](</docs/en/skills#frontmatter-reference>), so if you set it as a [scheduled task](</docs/en/scheduled-tasks>)’s prompt, Claude reads it as plain text instead of running the review. +### + +​ + +Let Claude start the review + +Claude can start `/code-review` on its own. Ask it to review your changes in plain language and it can run the skill without you typing the command, and a [scheduled task](</docs/en/scheduled-tasks>) with `/code-review` as its prompt runs the review. Exceptions include the following sessions, where `/code-review` runs only when you type it yourself and a scheduled `/code-review` reaches Claude as plain text instead of running the review: + + * **Cloud providers** : sessions on Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry, unless a host platform that embeds Claude Code sets [`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`](</docs/en/env-vars>) + * **Claude apps gateway** : sessions that connect through the [Claude apps gateway](</docs/en/claude-apps-gateway>) + * **Privacy environment variables** : sessions that opt out of telemetry or feature-flag fetching with [`DISABLE_TELEMETRY`, `DO_NOT_TRACK`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, or `DISABLE_GROWTHBOOK`](</docs/en/env-vars#variables>) + +A scheduled task never launches the cloud review, so schedule `/code-review` without the `ultra` argument. To stop both Claude and scheduled tasks from starting the review while keeping `/code-review` available for you to type, add a [`skillOverrides`](</docs/en/skills#override-skill-visibility-from-settings>) entry to a [settings file](</docs/en/settings#settings-files>) such as `~/.claude/settings.json`: + + { + "skillOverrides": { + "code-review": "user-invocable-only" + } + } + +From v2.1.215 through v2.1.222, Claude never started `/code-review` on its own in any configuration. ### @@ -371,7 +390,7 @@ Escalate to ultrareview -`/code-review ultra --fix` runs the deeper [ultrareview](</docs/en/ultrareview>) in the cloud, then applies its findings to your working tree when they arrive back in your session. Ultrareview uses its own scope: your current branch against the repository’s default branch, plus any uncommitted and staged changes in the working tree. Pass a branch name, such as `/code-review ultra develop`, to compare against a different base. +`/code-review ultra --fix` runs the deeper [ultrareview](</docs/en/ultrareview>) in the cloud, then applies its findings to your working tree when they arrive back in your session. Ultrareview uses its own scope: your current branch against the repository’s default branch, plus any uncommitted and staged changes in the working tree. Pass a branch name, such as `/code-review ultra develop`, to compare against a different base. When the target is a `github.com` pull request, you can have Claude [post the finished findings to the PR](</docs/en/ultrareview#post-findings-to-the-pull-request>) as a comment from your GitHub account. Requires Claude Code v2.1.227 or later. 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. @@ -382,8 +401,6 @@ ​ Related resources - -Code Review is designed to work alongside the rest of Claude Code. If you want to run reviews locally before opening a PR, need a self-hosted setup, or want to go deeper on how `CLAUDE.md` shapes Claude’s behavior across tools, these pages are good next stops: * [Commands](</docs/en/commands>): run `/code-review` in a local Claude Code session to check a diff before pushing * [GitHub Actions](</docs/en/github-actions>): run Claude in your own GitHub Actions workflows for custom automation beyond code review
modified Commands View current →
Show diff (130 lines)
--- a/commands.md +++ b/commands.md @@ -6,7 +6,7 @@ Commands across a typical workflow -Most commands are useful at a specific point in a session, from setting up a project to shipping a change. **First session in a repo.** Run `/init` to generate a starter `CLAUDE.md`, then `/memory` to refine it. Use `/mcp` to set up any servers the project needs, ask Claude to create any [subagents](</docs/en/sub-agents>) you want, and run `/permissions` to set your approval rules. **During a task.** `/plan` switches into plan mode before a large change. `/model` and `/effort` adjust which model you’re using and how much reasoning it applies. When the conversation gets long, `/context` shows what’s filling the window and `/compact` summarizes it to free space. Use `/btw` for a quick aside that shouldn’t add to the conversation history. **Run work in parallel.** Claude delegates side tasks to [subagents](</docs/en/sub-agents>), and `/tasks` lists the current session’s background work, including subagents that have finished. `/background` detaches the whole session to keep running as a [background agent](</docs/en/agent-view>) and frees your terminal. For a large change that spans the codebase, `/batch` decomposes it into independent units and runs each in its own [worktree](</docs/en/worktrees>). See [Run agents in parallel](</docs/en/agents>) for how these approaches relate. **Before you ship.** `/diff` shows what changed. `/code-review` checks the current diff for correctness bugs and cleanups and can apply the findings with `--fix`; pass a PR number, such as `/code-review high 1234`, to review a pull request instead. `/review` is an alias. `/code-review ultra` runs a multi-agent review in the cloud. `/security-review` checks the diff for security vulnerabilities. **Between sessions.** `/clear` starts fresh on a new task while keeping project memory. `/resume` returns to an earlier conversation, `/branch` branches the current one to try a different direction, and `/fork` copies it into a new [background session](</docs/en/agent-view>). `/teleport` pulls a web session into this terminal, and `/remote-control` lets you continue this local session from another device. **When something is wrong.** `/rewind` rolls code and conversation back to a checkpoint, or summarizes part of the conversation. `/doctor` runs a setup checkup that diagnoses installation and configuration issues and can fix them, `/debug` diagnoses runtime issues, and `/feedback` reports a bug with session context attached. +Most commands are useful at a specific point in a session, from setting up a project to shipping a change. **First session in a repo.** Run `/init` to generate a starter `CLAUDE.md`, then `/memory` to refine it. Use `/mcp` to set up any servers the project needs, ask Claude to create any [subagents](</docs/en/sub-agents>) you want, and run `/permissions` to set your approval rules. **During a task.** `/plan` switches into plan mode before a large change. `/model` and `/effort` adjust which model you’re using and how much reasoning it applies. When the conversation gets long, `/context` shows what’s filling the window and `/compact` summarizes it to free space. Use `/btw` for a side question that shouldn’t add to the conversation history. **Run work in parallel.** Claude delegates side tasks to [subagents](</docs/en/sub-agents>), and `/tasks` lists the current session’s background work, including subagents that have finished. `/background` detaches the whole session to keep running as a [background agent](</docs/en/agent-view>) and frees your terminal. For a large change that spans the codebase, `/batch` decomposes it into independent units and runs each in its own [worktree](</docs/en/worktrees>). See [Run agents in parallel](</docs/en/agents>) for how these approaches relate. **Before you ship.** `/diff` shows what changed. `/code-review` checks the current diff for correctness bugs and cleanups and can apply the findings with `--fix`; pass a PR number, such as `/code-review high 1234`, to review a pull request instead. `/review` is an alias. `/code-review ultra` runs a multi-agent review in the cloud. `/security-review` checks the diff for security vulnerabilities. **Between sessions.** `/clear` starts fresh on a new task while keeping project memory. `/resume` returns to an earlier conversation, `/branch` branches the current one to try a different direction, and `/fork` copies it into a new [background session](</docs/en/agent-view>). `/teleport` pulls a web session into this terminal, and `/remote-control` lets you continue this local session from another device. **When something is wrong.** `/rewind` rolls code and conversation back to a checkpoint, or summarizes part of the conversation. `/doctor` runs a setup checkup that diagnoses installation and configuration issues and can fix them, `/debug` diagnoses runtime issues, and `/feedback` reports a bug with session context attached. ## @@ -17,8 +17,9 @@ The table below lists all the commands included in Claude Code. Most are built-in commands whose behavior is coded into the CLI. Two kinds of entries are marked: * **[Skill](</docs/en/skills#bundled-skills>)** : a bundled skill. It works like skills you write yourself: a prompt handed to Claude, which Claude can also invoke automatically when relevant. - * `/verify` and `/code-review` run only when you invoke them. Before v2.1.215, Claude could also run them on its own. + * `/verify` runs only when you invoke it. Before v2.1.215, Claude could also run `/verify` on its own. * **[Workflow](</docs/en/workflows#bundled-workflows>)** : a bundled [dynamic workflow](</docs/en/workflows>) that fans work out across many subagents and runs in the background. + * `/deep-research` runs only when you invoke it. Before v2.1.218, Claude could also start it on its own. To add your own commands, see [skills](</docs/en/skills>). In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one. @@ -26,25 +27,25 @@ Command| Purpose ---|--- -`/add-dir <path>`| Add a working directory for file access during the current session. Typing a partial path shows matching directory suggestions; press `Tab` to accept one. Most `.claude/` configuration is [not discovered](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) from the added directory. You can later resume the session from the added directory with `--continue` or `--resume` +`/add-dir <path>`| Add a working directory for file access during the current session. Type a partial path to see matching directory suggestions; press `Tab` to accept one. Most `.claude/` configuration is [not discovered](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) from the added directory. A successful add runs your [`DirectoryAdded` hooks](</docs/en/hooks#directoryadded>) `/advisor [model|off]`| Enable or disable the [advisor tool](</docs/en/advisor>), which consults a second model for guidance at key moments during a task. Accepts `opus`, `sonnet`, or a full model ID. Claude Code [doesn’t offer Fable 5 as the advisor](</docs/en/advisor#enable-the-advisor>) and rejects `/advisor fable`. Without an argument, opens a picker `/agents`| As of v2.1.198, running `/agents` prints a reminder to ask Claude to create or manage [subagents](</docs/en/sub-agents>), or to edit `.claude/agents/` or `~/.claude/agents/` directly. On v2.1.197 and earlier, opens an interactive interface for creating and managing subagent configurations -`/autocompact [auto|<tokens>]`| Set the auto-compact window: how full the context window gets before Claude Code compacts automatically. Pass a size such as `500k`, or `auto` to return to the window tuned for your model. Claude Code saves the value to user settings and applies it to the current session. See [Set the auto-compact window](</docs/en/context-window#set-the-auto-compact-window>) for accepted values and what overrides it. Without an argument, opens a dialog that shows the current window. Requires Claude Code v2.1.221 or later +`/autocompact [auto|<tokens>]`| Set the auto-compact window: how full the context window gets before Claude Code compacts automatically. Pass a size such as `500k`, or `auto` to return to the window tuned for your model. Claude Code saves the value to user settings and applies it to the current session. See [Set the auto-compact window](</docs/en/model-config#set-the-auto-compact-window>) for accepted values and what overrides it. Without an argument, opens a dialog that shows the current window. Requires Claude Code v2.1.221 or later `/autofix-pr [prompt]`| Spawn a [Claude Code on the web](</docs/en/claude-code-on-the-web#auto-fix-pull-requests>) session that watches the current branch’s PR and pushes fixes when CI fails or reviewers leave comments. Detects the open PR from your checked-out branch with `gh pr view`; to watch a different PR, check out its branch first. By default the cloud session is told to fix every CI failure and review comment; pass a prompt to give it different instructions, for example `/autofix-pr only fix lint and type errors`. Requires the `gh` CLI and access to [Claude Code on the web](</docs/en/claude-code-on-the-web>) `/background [prompt]`| Detach the current session to run as a [background agent](</docs/en/agent-view>) and free this terminal. Pass a prompt to send one more instruction before detaching. Monitor the session with `claude agents`. To copy the conversation into a new background session while this one keeps running, use `/fork`. Alias: `/bg` `/batch <instruction>`| **[Skill](</docs/en/skills#bundled-skills>).** Orchestrate large-scale changes across a codebase in parallel. Researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once approved, spawns one [background subagent](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) per unit in an isolated [git worktree](</docs/en/worktrees>). Each subagent implements its unit, runs tests, and opens a pull request. Requires a git repository. Example: `/batch migrate src/ from Solid to React` `/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 quick [side question](</docs/en/interactive-mode#side-questions-with-%2Fbtw>) without adding to the conversation. Without a question, reopens the overlay on your most recent side question from this session so you can browse earlier answers; with no side questions yet, it asks for one. Before v2.1.212, `/btw` required a question +`/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. Alias: `/share`. Before v2.1.212, `/bug` and `/share` were aliases of `/feedback` -`/cd <path>`| Move this session to a new working directory. The conversation’s prompt cache is preserved: the new directory’s [`CLAUDE.md`](</docs/en/memory>) is appended as a message instead of rebuilding the system prompt. The session is relocated to the new directory’s project storage, so `--resume` and `--continue` find it from there. `claude --resume <session-id>` also [finds the moved session from any other directory](</docs/en/sessions#resume-a-session>); this requires Claude Code v2.1.223 or later. Prompts you to trust the directory if you haven’t worked in it before. Typing a partial path shows matching directory suggestions; press `Tab` to accept one. The suggestions require Claude Code v2.1.206 or later. 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; earlier versions report `Unknown command: /cd` +`/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. 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 `/chrome`| Configure [Claude in Chrome](</docs/en/chrome>) settings `/claude-api [migrate|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 upgrade existing Claude API code to a newer model, `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 `/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>). Aliases: `/reset`, `/new` -`/code-review [low|medium|high|xhigh|max|ultra] [--fix] [--comment] [pr#|branch|path]`| **[Skill](</docs/en/skills#bundled-skills>).** Review the current diff, or a PR number, branch, or path you pass, for correctness bugs and cleanup opportunities. Pass `--fix` to apply findings, `--comment` to post them as inline GitHub PR comments, or `ultra` to run a deep [cloud review](</docs/en/ultrareview>). With no level given, the review reuses the last `low` through `max` level you typed. A local review runs as a [subagent](</docs/en/sub-agents>), in the background in interactive sessions, so it doesn’t fill your conversation; before v2.1.218, it ran inside your conversation. See [Review a diff locally](</docs/en/code-review#review-a-diff-locally>) for the exact effort rules, targeting, and how it relates to `/simplify`. Alias: `/review` +`/code-review [low|medium|high|xhigh|max|ultra] [--fix] [--comment] [pr#|branch|path]`| **[Skill](</docs/en/skills#bundled-skills>).** Review the current diff, or a PR number, branch, or path you pass, for correctness bugs and cleanup opportunities. Pass `--fix` to apply findings, `--comment` to post them as inline GitHub PR comments, or `ultra` to run a deep [cloud review](</docs/en/ultrareview>). With `ultra` on a `github.com` PR target, `--post` preselects [posting the finished findings to the PR](</docs/en/ultrareview#post-findings-to-the-pull-request>) in the launch dialog. See [Review a diff locally](</docs/en/code-review#review-a-diff-locally>) for the effort levels, targeting, and how it relates to `/simplify`. Alias: `/review` `/color [color|default]`| Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset, or run with no argument to pick a random color. When [Remote Control](</docs/en/remote-control>) is connected, the color syncs to claude.ai/code. Also available in non-interactive mode (`-p`); requires Claude Code v2.1.205 or later `/compact [instructions]`| Free up context by summarizing the conversation so far. Optionally pass focus instructions for the summary. See [how compaction handles rules, skills, and memory files](</docs/en/context-window#what-survives-compaction>) `/config [key=value ...]`| Open the [Settings](</docs/en/settings>) interface to adjust theme, model, [output style](</docs/en/output-styles>), and other preferences. From v2.1.181, pass one or more `key=value` pairs to set a setting directly without opening the interface, for example `/config thinking=false`. From v2.1.182, named shorthand keys are also accepted, such as `/config theme=dark` or `/config model=sonnet`. The `key=value` form also works in non-interactive mode (`-p`) and from the Claude mobile app via [Remote Control](</docs/en/remote-control>). Run `/config --help` to list every settable key with its options. Alias: `/settings` -`/context [all]`| Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings. When the conversation exceeds the context window, the output includes a [warning](</docs/en/errors#context-exceeds-the-token-limit>) showing how far over the limit you are and which command frees space; this warning requires Claude Code v2.1.216 or later. In [fullscreen mode](</docs/en/fullscreen>), `/context` collapses the per-item breakdown to keep the grid visible. Pass `all` to expand it +`/context [all]`| Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings. When the conversation exceeds the context window, the output includes a [warning](</docs/en/errors#context-exceeds-the-token-limit>) showing how far over the limit you are and which command frees space. In [fullscreen mode](</docs/en/fullscreen>), `/context` collapses the per-item breakdown to keep the grid visible. Pass `all` to expand it `/copy [N]`| Copy the last assistant response to clipboard. Pass a number `N` to copy the Nth-latest response: `/copy 2` copies the second-to-last. When code blocks are present, shows an interactive picker to select individual blocks or the full response. Press `w` in the picker to write the selection to a file instead of the clipboard, which is useful over SSH `/cost`| Alias for `/usage` `/dataviz [request]`| **[Skill](</docs/en/skills#bundled-skills>).** Design guidance for charts, graphs, and dashboards. Claude picks the chart form for the data, assigns color by role, validates the palette for colorblind safety and contrast with a bundled script, and applies mark, interaction, and accessibility rules. Uses a brand-neutral placeholder palette that you replace with your own. Requires Claude Code v2.1.198 or later @@ -54,14 +55,14 @@ `/design-sync [hint]`| **[Skill](</docs/en/skills#bundled-skills>).** Convert your repo’s React design system and upload it to [Claude Design](<https://claude.ai/design>), so designs it produces use your real components. Optionally name the design system, for example `/design-sync Acme DS`. A first-time sync verifies every component and can take a few hours on a large repo. Available on the Anthropic API; on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and Claude Platform on AWS the underlying tool can’t reach claude.ai, so the command is unavailable `/desktop`| Continue the current session in the Claude Code Desktop app. Requires macOS or x64 Windows and a Claude subscription. Alias: `/app` `/diff`| Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files. Press Enter to open the selected file’s diff, scroll it with up/down or PageUp/PageDown, and press Esc to return to the file list. Claude Code computes these diffs from raw git blob content, so diff drivers and `textconv` filters configured in `.gitattributes` or git config don’t apply. Before v2.1.222, workspace-configured drivers and filters could rewrite the viewer’s output. The open viewer also refreshes automatically when the repository’s git state changes outside the session, such as a branch switch or commit in another terminal; the auto-refresh requires Claude Code v2.1.198 or later -`/doctor`| **[Skill](</docs/en/skills#bundled-skills>).** Run a setup checkup that diagnoses issues and can fix them. Checks installation health, including duplicate or leftover installs, `PATH` problems, and unparseable settings files. Finds unused skills, MCP servers, and plugins versus their context cost, flags slow [hooks](</docs/en/hooks>), and checks for a newer version on your release channel. Deduplicates local `CLAUDE.md` files against checked-in ones, trims checked-in [`CLAUDE.md`](</docs/en/memory>) files by cutting content Claude could derive from the codebase, and migrates the always-loaded guidance that remains into [skills](</docs/en/skills>) and nested `CLAUDE.md` files that load on demand. The trim cuts sections such as directory layouts, dependency lists, and architecture overviews, and keeps pitfalls, rationale, and conventions that differ from tool defaults. Also offers to make [auto mode](</docs/en/permissions#permission-modes>) your default and to [pre-approve](</docs/en/permissions>) frequently denied read-only commands. Reports findings first and asks for confirmation before changing anything. From the terminal, `claude doctor` prints read-only installation diagnostics without starting a session. Alias: `/checkup`. The `CLAUDE.md` trim check requires Claude Code v2.1.206 or later. Before v2.1.206, the version check compared Homebrew installs against the `autoUpdatesChannel` setting rather than the [installed cask’s channel](</docs/en/setup#configure-release-channel>). Before v2.1.205, `/doctor` opened a read-only diagnostics screen and pressing `f` sent the report to Claude +`/doctor`| **[Skill](</docs/en/skills#bundled-skills>).** Run a setup checkup that diagnoses issues and can fix them. Checks installation health, including duplicate or leftover installs, `PATH` problems, and unparseable settings files. Finds unused skills, MCP servers, and plugins versus their context cost, flags slow [hooks](</docs/en/hooks>), and checks for a newer version on your [release channel](</docs/en/setup#configure-release-channel>). Deduplicates local `CLAUDE.md` files against checked-in ones, trims checked-in [`CLAUDE.md`](</docs/en/memory#my-claude-md-is-too-large>) files by cutting content Claude could derive from the codebase, and migrates the always-loaded guidance that remains into [skills](</docs/en/skills>) and nested `CLAUDE.md` files that load on demand. Also offers to make [auto mode](</docs/en/permissions#permission-modes>) your default and to [pre-approve](</docs/en/permissions>) frequently denied read-only commands. Reports findings first and asks for confirmation before changing anything. From the terminal, `claude doctor` prints read-only installation diagnostics without starting a session. Alias: `/checkup`. The `CLAUDE.md` trim check requires Claude Code v2.1.206 or later. Before v2.1.205, `/doctor` opened a read-only diagnostics screen and pressing `f` sent the report to Claude `/effort [level|auto]`| Set the model [effort level](</docs/en/model-config#adjust-effort-level>). Accepts `low`, `medium`, `high`, `xhigh`, `max`, or [`ultracode`](</docs/en/workflows#let-claude-decide-with-ultracode>); available levels depend on the model, and `max` and `ultracode` are session-only. `auto` resets to the model default. Without an argument, opens an interactive slider. Takes effect immediately without waiting for the current response to finish. Also available in non-interactive mode (`-p`) with a level argument, where it applies to the current session only; requires Claude Code v2.1.205 or later. While the [model-default effort hold](</docs/en/model-config#adjust-effort-level>) is in force, a non-interactive `/effort` reports `Not applied`, so pass `--effort` at launch instead `/exit`| Exit the CLI. In an attached [background session](</docs/en/agent-view#attach-to-a-session>), this detaches and the session keeps running. Alias: `/quit` `/export [filename]`| Export the current conversation as plain text. With a filename, writes directly to that file. Without, opens a dialog to copy to clipboard or save to a file `/fast [on|off]`| Toggle [fast mode](</docs/en/fast-mode>) on or off. In non-interactive mode (`-p`), `/fast` works only in a session launched with fast mode in its [`--settings`](</docs/en/cli-reference#cli-flags>) value, for example `claude -p --settings '{"fastMode": true}'`; the toggle then applies to the current session only and isn’t saved as your default, and in any other non-interactive session the command reports that fast mode isn’t available. Requires Claude Code v2.1.205 or later `/feedback [report]`| Send product feedback about Claude Code. Opens the same dialog as `/bug` with the same consent step and sending rules `/fewer-permission-prompts`| **[Skill](</docs/en/skills#bundled-skills>).** Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project `.claude/settings.json` to reduce permission prompts -`/focus`| Toggle the focus view, which shows only your last prompt, a one-line tool-call summary with edit diffstats, and the final response. As of v2.1.198, the tool-call summary also counts the subagents launched in the turn and collapses completed background-task notifications into a single count. The selection persists across sessions; set [`viewMode`](</docs/en/settings#available-settings>) in settings to override it. Only available in [fullscreen rendering](</docs/en/fullscreen>). The [VS Code extension](</docs/en/vs-code#use-the-prompt-box>) offers its own Focus view as a command-menu toggle, stored as an extension setting, independent of `viewMode` +`/focus`| Toggle the focus view, which shows only your last prompt, a one-line tool-call summary with edit diffstats, and the final response. The tool-call summary also counts the subagents launched in the turn and collapses completed background-task notifications into a single count. The selection persists across sessions; set [`viewMode`](</docs/en/settings#available-settings>) in settings to override it. Only available in [fullscreen rendering](</docs/en/fullscreen>). The [VS Code extension](</docs/en/vs-code#use-the-prompt-box>) offers its own Focus view as a command-menu toggle, stored as an extension setting, independent of `viewMode` `/fork [prompt]`| [Copy the current conversation](</docs/en/agent-view#copy-the-session-with-%2Ffork>) into a new background session and keep working here. Pass a prompt and the copy starts working on it immediately; without one it waits in agent view for its first prompt. Except when the copy [edits in place](</docs/en/agent-view#how-file-edits-are-isolated>), Claude Code instructs it to create a worktree of its own before making code changes; the isolation instruction requires Claude Code v2.1.221 or later. To hand a side task to a subagent whose result comes back into this conversation, use `/subtask`; to switch into a copy yourself, use `/branch`. Requires Claude Code v2.1.212 or later; on v2.1.161 through v2.1.211, and whenever [agent view is turned off](</docs/en/agent-view#turn-off-agent-view>), `/fork` starts a [forked subagent](</docs/en/sub-agents#fork-the-current-conversation>) instead `/goal [condition|clear]`| Set a [goal](</docs/en/goal>): Claude keeps working across turns until the condition is met. With no argument, shows the current or most recently achieved goal. `clear`, `stop`, `off`, `reset`, `none`, or `cancel` removes an active goal early `/heapdump`| Write a JavaScript heap snapshot and a memory breakdown to `~/Desktop`, or your home directory on Linux without a Desktop folder, for diagnosing high memory usage. Attach only the `-diagnostics.json` file when reporting a memory issue; the `.heapsnapshot` contains your full conversation and credentials, so don’t share it. Doesn’t appear in the command menu; type it in full. See [what to do with the output](</docs/en/troubleshooting#high-cpu-or-memory-usage>) @@ -70,7 +71,7 @@ `/ide`| Manage IDE integrations and show status `/import [codex|gemini] [--dry-run] [--yes]`| Bring configuration from other coding agents on your machine, currently OpenAI Codex and Google Gemini CLI, into Claude Code, including instruction files, MCP servers, commands, subagents, and skills. In [non-interactive mode](</docs/en/headless>) with `-p`, `/import` lists what it found and gives you the command that confirms the import. Add `--dry-run` to preview without writing anything, or `--yes` to skip the interactive picker. Requires Claude Code v2.1.213 or later `/init`| Initialize project with a `CLAUDE.md` guide. Set `CLAUDE_CODE_NEW_INIT=1` for an interactive flow that also walks through skills, hooks, and personal memory files. If `/init` finds configuration from a coding agent that `/import` supports, it offers to carry it over with `/import` -`/insights`| Generate a report analyzing your Claude Code sessions, including project areas, interaction patterns, and friction points +`/insights`| Generate an HTML report analyzing your recent sessions on this machine: which projects you work in, how you use Claude Code, where things go wrong, and features to try. Not available in [cloud sessions](</docs/en/claude-code-on-the-web>). See [Analyze your usage patterns](</docs/en/costs#analyze-your-usage-patterns>) for the report location, retention, and cost `/install-github-app`| Install the Claude GitHub App for a repository, with an optional step to set up [GitHub Actions](</docs/en/github-actions>) workflows and secrets. Walks you through selecting a repo and configuring the integration `/install-slack-app`| Install the Claude Slack app. Opens a browser to complete the OAuth flow `/keybindings`| Open your [keyboard shortcuts](</docs/en/keybindings>) file @@ -79,7 +80,7 @@ `/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 Claude self-paces between iterations. Omit the prompt and, [where available](</docs/en/scheduled-tasks#run-the-built-in-maintenance-prompt>), 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` `/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` memory files, enable or disable [auto-memory](</docs/en/memory#auto-memory>), and view auto-memory entries +`/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` `/model [model]`| Switch the AI model and save it as your default for new sessions. For models that support it, use left/right arrows to [adjust effort level](</docs/en/model-config#adjust-effort-level>). With no argument, opens a picker; press `s` on a row to switch for the current session only. The picker asks for confirmation when the conversation has prior output, since the next response re-reads the full history without cached context. Once confirmed, the change applies without waiting for the current response to finish. Also available in non-interactive mode (`-p`) with a model argument instead of the picker, where it applies to the current session only and isn’t saved as your default; requires Claude Code v2.1.205 or later `/passes`| Share a free week of Claude Code with friends. Only visible if your account is eligible @@ -91,19 +92,19 @@ `/privacy-settings`| View and update your privacy settings. Only available for Pro and Max plan subscribers `/radio`| Open Claude FM lo-fi radio in your browser. Prints the stream URL when no browser is available. Not available on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or Claude Platform on AWS `/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. Before v2.1.208, the viewed notes entered the conversation, including the entire changelog when showing all versions +`/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 `/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 -`/resume [session]`| Resume a conversation by ID or name, or open the session picker. As of v2.1.144, [background sessions](</docs/en/agent-view>) appear in the picker marked with `bg`; one that is still running can’t be resumed here, so attach to it from `claude agents` or stop it there first. Alias: `/continue` +`/resume [session]`| Resume a conversation by ID or name, or open the session picker. [Background sessions](</docs/en/agent-view>) appear in the picker marked with `bg`; one that is still running can’t be resumed here, so attach to it from `claude agents` or stop it there first. Alias: `/continue` `/review [low|medium|high|xhigh|max|ultra] [--fix] [--comment] [pr#|branch|path]`| Alias of [`/code-review`](</docs/en/code-review#review-a-diff-locally>): reviews the current diff, or a PR number, branch, or path you pass, such as `/review 1234`, and takes the same effort levels and flags. With no level given, the review reuses the last `low` through `max` level you typed; see [Review a diff locally](</docs/en/code-review#review-a-diff-locally>) for the exact rules. For a deep cloud review, use [`/code-review ultra`](</docs/en/ultrareview>). Before v2.1.223, `/review` was a separate command that ran a single-pass, read-only review of a GitHub pull request by number, listing open PRs to pick from when run with no argument; from v2.1.186 through v2.1.201, it ran the same multi-agent engine as `/code-review medium` `/rewind`| Rewind the conversation and/or code to a previous point, or summarize from a selected message. See [checkpointing](</docs/en/checkpointing>). Aliases: `/checkpoint`, `/undo` `/run`| **[Skill](</docs/en/skills#bundled-skills>).** Launch and drive your project’s app to see a change working, not only passing tests. See [Run and verify your app](</docs/en/skills#run-and-verify-your-app>). Requires Claude Code v2.1.145 or later `/run-skill-generator`| **[Skill](</docs/en/skills#bundled-skills>).** Teach `/run` and `/verify` how to build, launch, and drive your project’s app from a clean environment by writing a per-project [skill](</docs/en/skills#run-and-verify-your-app>). Requires Claude Code v2.1.145 or later `/sandbox`| Toggle [sandbox mode](</docs/en/sandboxing>). Available on supported platforms only -`/schedule [description]`| Create, update, list, or run [routines](</docs/en/routines>), which execute in the cloud. Claude walks you through the setup conversationally. Alias: `/routines` +`/schedule [description]`| Create, update, list, or run [routines](</docs/en/routines>), which execute in the cloud. Claude walks you through the setup conversationally. You can also ask about a [routine’s recent runs](</docs/en/routines#manage-routines-from-the-cli>). Alias: `/routines` `/scroll-speed`| Adjust mouse wheel [scroll speed](</docs/en/fullscreen#mouse-wheel-scrolling>) interactively, with a ruler you can scroll while the dialog is open to preview the change. Available in [fullscreen rendering](</docs/en/fullscreen>) only and not in the JetBrains IDE terminal `/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. Only visible when `CLAUDE_CODE_USE_BEDROCK=1` is set. First-time Amazon Bedrock users can also access this wizard from the login screen @@ -118,7 +119,7 @@ `/subtask <task>`| Spawn a [forked subagent](</docs/en/sub-agents#fork-the-current-conversation>): a background subagent that inherits the full conversation and works on the task while you keep working. Its result returns to this conversation when it finishes. To copy the conversation into a separate background session instead, use `/fork`. Requires Claude Code v2.1.212 or later; on v2.1.161 through v2.1.211 this command is `/fork`. When [agent view is turned off](</docs/en/agent-view#turn-off-agent-view>), `/subtask` isn’t available and `/fork` keeps the forked-subagent behavior `/tasks`| View and manage background work in the current session, including subagents that have finished. Also available as `/bashes` `/team-onboarding`| Generate a team onboarding guide from your Claude Code usage history. Claude analyzes your sessions, commands, and MCP server usage from the past 30 days and produces a markdown guide a teammate can paste as a first message to get set up quickly. For claude.ai subscribers on Pro, Max, Team, and Enterprise plans, also returns a share link teammates can open directly in Claude Code -`/teleport`| Pull a [Claude Code on the web](</docs/en/claude-code-on-the-web#from-web-to-terminal>) session into this terminal: opens a picker, then fetches the branch and conversation. Also available as `/tp`. Requires a claude.ai subscription +`/teleport`| Pull a [Claude Code on the web](</docs/en/claude-code-on-the-web#from-web-to-terminal>) session into this terminal. Opens a picker, then fetches the branch and conversation. Also available as `/tp`. Requires a claude.ai subscription `/terminal-setup`| Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Cursor, Devin Desktop, Alacritty, or Zed `/theme`| Change the color theme. Includes an `auto` option that matches your terminal’s light or dark background, light and dark variants, colorblind-accessible (daltonized) themes, ANSI themes that use your terminal’s color palette, and any [custom themes](</docs/en/terminal-config#create-a-custom-theme>) from `~/.claude/themes/` or plugins. Select **New custom theme…** to create one `/tui [default|fullscreen]`| Set the terminal UI renderer and relaunch into it with your conversation intact. `fullscreen` enables the [flicker-free alt-screen renderer](</docs/en/fullscreen>). With no argument, prints the active renderer @@ -126,7 +127,7 @@ `/ultrareview [PR or branch]`| Run a deep, multi-agent code review in a cloud sandbox with [ultrareview](</docs/en/ultrareview>). Pass a PR reference to review that pull request, or a branch name to change the comparison base. The preferred invocation is now `/code-review ultra`, and `/ultrareview` remains as an alias. Includes 3 free runs on Pro and Max, then requires [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) `/upgrade`| Open the upgrade page in your browser to switch to a higher plan tier. When the browser fails to open, the command shows a sign-in prompt without printing the URL `/usage`| Show session cost, plan usage limits, and activity stats. On a Pro, Max, Team, or Enterprise plan, includes a breakdown of usage by skill, subagent, plugin, and MCP server. See the [cost tracking guide](</docs/en/costs#using-the-%2Fusage-command>) for details. `/cost` and `/stats` are aliases -`/usage-credits`| Configure usage credits, or request them from your admin, when you hit a limit. Opens your [usage-credits billing settings](</docs/en/costs#add-usage-credits-to-your-subscription>) in the browser, except that Team and Enterprise members without billing access instead send a usage-credits request to their admin from the CLI, after confirming in a dialog that the request notifies their admins. Before v2.1.211, Claude Code sent the request without a confirmation step. When no browser can open the billing page, for example over SSH, the command prints the URL to visit instead; this requires Claude Code v2.1.205 or later, and earlier versions showed nothing in that case. Previously `/extra-usage` +`/usage-credits`| Configure usage credits, or request them from your admin, when you hit a limit. Opens your [usage-credits billing settings](</docs/en/costs#add-usage-credits-to-your-subscription>) in the browser, except that Team and Enterprise members without billing access instead send a usage-credits request to their admin from the CLI, after confirming in a dialog that the request notifies their admins. When no browser can open the billing page, for example over SSH, the command prints the URL to visit instead; this requires Claude Code v2.1.205 or later, and earlier versions showed nothing in that case. Previously `/extra-usage` `/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>). Requires Claude Code v2.1.145 or later `/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
modified Communications kit View current →
--- a/communications-kit.md +++ b/communications-kit.md @@ -195,7 +195,7 @@ Tips and tricks campaign -Ready-to-paste Slack or Teams messages designed to drive feature activation after launch. Each follows the same pattern: a hook, the payoff, a “try it now” prompt, and a docs link. Drip them one or two a week in `#claude-code`, or pick the handful that match your team’s gaps. They stand alone with no required order. Copy the message body from each block directly into Slack or Teams. Replace `[bracketed placeholders]` before sending. +Ready-to-paste Slack or Teams messages designed to drive feature activation after launch. Each follows the same pattern: a hook, the payoff, a “try it now” prompt, and a docs link. Drip them one or two a week in `#claude-code`, or pick the handful that match your team’s gaps. They stand alone with no required order. ###
modified Let Claude use your computer from the CLI View current →
--- a/computer-use.md +++ b/computer-use.md @@ -106,7 +106,7 @@ One session at a time -Computer use holds a machine-wide lock from the first computer use action until the session that took it exits. As of v2.1.195, finishing the task doesn’t release the lock; only exiting the session does. If another Claude Code session is already using your computer, new attempts fail with a message telling you which session holds the lock. Exit that session first. +Only one session at a time can use your computer. Claude Code takes a machine-wide lock when a session performs its first computer use action. Claude Code releases it when that session exits, not when the task finishes. If another session is already using your computer, Claude Code rejects new attempts and tells you which session holds the lock. Exit that session first. ###
modified Explore the context window View current →
--- a/context-window.md +++ b/context-window.md @@ -42,37 +42,11 @@ Claude Code compacts automatically as you approach the limit, so a full context window doesn’t end your session. The automatic pass works the same way as the `/compact` step in the timeline. See [When context fills up](</docs/en/how-claude-code-works#when-context-fills-up>) for what it preserves. You can also act before the automatic pass runs: * **Compact with a focus** : run `/compact` with instructions, like `/compact focus on the auth bug fix`, before starting a long new task. The summary keeps what you choose instead of what the automatic pass guesses is important. - * **Compact earlier** : run [`/autocompact`](</docs/en/commands#all-commands>) with a token count, like `/autocompact 500k`, to set how full the context window gets before the automatic pass runs. See Set the auto-compact window for accepted values and overrides. + * **Compact earlier** : run [`/autocompact`](</docs/en/commands#all-commands>) with a token count, like `/autocompact 500k`, to set how full the context window gets before the automatic pass runs. See [Set the auto-compact window](</docs/en/model-config#set-the-auto-compact-window>) for accepted values and overrides. * **Clear between tasks** : run `/clear` when switching to unrelated work. Old conversation crowds out the files you need next and costs tokens on every message. * **Delegate large reads** : send research to a [subagent](</docs/en/sub-agents>) so the file contents stay in its context window, not yours. -If you need a larger window rather than a smaller conversation, Fable 5, Sonnet 5, Opus 4.6 and later, and Sonnet 4.6 support a 1 million token context window. See [Extended context](</docs/en/model-config#extended-context>) for availability by plan and how to select a `[1m]` model variant. Sonnet 5 runs at 1M with no `[1m]` variant to select; see [Sonnet 5 context window](</docs/en/model-config#sonnet-5-context-window>) for its auto-compaction thresholds and the LLM gateway exception. Compaction works the same way at the larger limit. - -### - -​ - -Set the auto-compact window - -The auto-compact window is how full the context window can get before Claude Code compacts the conversation. You can set it in three places: - - * **For this session and later ones** : run `/autocompact` with a value, like `/autocompact 500k`. Claude Code saves it to your user settings as [`autoCompactWindow`](</docs/en/settings#available-settings>) and applies it to the current session; if a higher-priority [settings scope](</docs/en/settings#settings-precedence>) such as managed settings sets the key, the command saves your value but the session keeps that scope’s window, and the command says so. Run `/autocompact auto` to return to the window tuned for your model. - * **For one launch** : pass [`--autocompact`](</docs/en/cli-reference#cli-flags>) when starting Claude Code. The flag overrides your saved setting for that launch without changing it, and `claude --autocompact auto` runs the session at the tuned window even if your saved setting has a value. Unlike `/autocompact`, the flag isn’t preempted by a higher-priority settings scope such as managed settings. - * **In scripts and cloud environments** : set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>). While it’s set, it takes precedence over the command, the flag, and the setting, and `/autocompact` reports the override instead of changing the window. - -The command and the flag accept a window size from 100K to 1M tokens, in any of these forms: - - * A plain token count, such as `200000` - * A `k` or `M` suffix, such as `500k` or `1M` - * A bare number from 100 to 1000, meaning thousands, so `200` sets 200,000 - -The environment variable accepts only the plain token count. Claude Code caps the window at the model’s context window. With no window size set in any of these places, Claude Code compacts when the conversation reaches the model’s context limit, except in these sessions: - - * [Cloud sessions](</docs/en/claude-code-on-the-web>) compact as the conversation approaches the model’s limit - * Sonnet 4.6 and Opus 4.6 without [extended context](</docs/en/model-config#extended-context>) compact at the 200K boundary, and so do Opus 4.8 and Opus 5 when they run with a 200K context window, such as on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry - * When you set [`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`](</docs/en/env-vars>), models with a native 1M window, such as Sonnet 5 and Fable 5, compact at the 200K boundary. Before v2.1.223, Claude Code held only Sonnet 5, Opus 4.8, and Opus 5 sessions to 200K - * Sonnet 5 compacts at the [threshold for its configuration](</docs/en/model-config#sonnet-5-context-window>) - * Sessions on a model ID Claude Code doesn’t recognize, such as an [LLM gateway](</docs/en/llm-gateway>) alias, compact at the context window Claude Code assumes for the ID. If the ID doesn’t start with `claude-`, set [`CLAUDE_CODE_MAX_CONTEXT_TOKENS`](</docs/en/env-vars>) to correct the assumed window while keeping proactive compaction. Set [`CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT=1`](</docs/en/env-vars>) to have Claude Code compact only after the API rejects the conversation with Anthropic’s too-long error; that recovery doesn’t run when a gateway [rewrites the error](</docs/en/llm-gateway-connect#troubleshoot-gateway-errors>) +If you need a larger window rather than a smaller conversation, Fable 5, Sonnet 5, Opus 4.6 and later, and Sonnet 4.6 support a 1 million token context window. See [Extended context](</docs/en/model-config#extended-context>) for availability by plan and how to select a `[1m]` model variant. Sonnet 5 runs at 1M with no `[1m]` variant to select; see [Sonnet 5 context window](</docs/en/model-config#sonnet-5-context-window>) for its auto-compaction thresholds and the LLM gateway exception. Compaction works the same way at the larger limit. The point where automatic compaction runs depends on your model and configuration. See [Default auto-compact thresholds](</docs/en/model-config#default-auto-compact-thresholds>) for the boundaries per model, and [Correct the window for a gateway or custom model ID](</docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id>) if Claude Code assumes the wrong window for your model ID, such as an [LLM gateway](</docs/en/llm-gateway>) alias. ##
modified Track cost and usage View current →
Show diff (174 lines)
--- a/cost-tracking.md +++ b/cost-tracking.md @@ -17,11 +17,11 @@ The TypeScript and Python SDKs expose the same usage data with different field names: * **TypeScript** provides per-step token breakdowns on each assistant message (`message.message.id`, `message.message.usage`), per-model cost via `modelUsage` on the result message, and a cumulative total on the result message. - * **Python** provides per-step token breakdowns on each assistant message (`message.usage`, `message.message_id`), per-model cost via `model_usage` on the result message, and the accumulated total on the result message (`total_cost_usd` and `usage` dict). + * **Python** provides per-step token breakdowns on each assistant message as `message.usage` and `message.message_id`, per-model cost via `model_usage` on the result message, and the cumulative total on the result message as `total_cost_usd`. Both SDKs use the same underlying cost model and expose the same granularity. The difference is in field naming and where per-step usage is nested. Cost tracking depends on understanding how the SDK scopes usage data: - * **`query()` call:** one invocation of the SDK’s `query()` function. A single call can involve multiple steps (Claude responds, uses tools, gets results, responds again). Each call produces one [`result`](</docs/en/agent-sdk/typescript#sdkresultmessage>) message at the end. + * **`query()` call:** one invocation of the SDK’s `query()` function. A single call can involve multiple steps: Claude responds, uses tools, gets results, and responds again. Each call produces one [`result`](</docs/en/agent-sdk/typescript#sdkresultmessage>) message at the end, except in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), where one `query()` call carries multiple user turns and each turn emits its own `result` message. * **Step:** a single request/response cycle within a `query()` call. Each step produces assistant messages with token usage. * **Session:** a series of `query()` calls linked by a session ID (using the `resume` option). Each `query()` call within a session reports its own cost independently. @@ -37,7 +37,26 @@ The result message provides the cumulative estimate -When the `query()` call completes, the SDK emits a result message with `total_cost_usd` and cumulative `usage`. This is available in both TypeScript ([`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>)) and Python ([`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>)). If you make multiple `query()` calls (for example, in a multi-turn session), each result only reflects the cost of that individual call. If you only need the estimated total, you can ignore the per-step usage and read this single value. +When the `query()` call completes, the SDK emits a result message with `total_cost_usd` and cumulative `usage`, typed as [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) in TypeScript and [`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>) in Python. If you make multiple `query()` calls, for example in a multi-turn session, each result reflects only the cost of that individual call. If you only need the estimated total, you can ignore the per-step usage and read this single value.In streaming input mode, each turn emits its own result message. See Track costs in streaming input mode for how to read call totals in that mode. + +## + +​ + +Track costs in streaming input mode + +In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), one `query()` call carries multiple user turns and each turn emits its own result message. The result fields differ in scope: + + * **`usage`** : covers only that turn, and within it only the main agent loop, not any subagents it ran. + * **`total_cost_usd` and `modelUsage`, or `model_usage` in Python**: carry the running total for the whole call so far. + +In a call where your app never sends `/clear`, `/reset`, or `/new`, read the latest result for call totals rather than summing across results. The running totals start over each time your app sends one of those three commands, and inside a `query()` call nothing else resets them. Three results matter for your accounting: + + * **The`/clear` turn’s own result**: covers only what has run since the reset, and carries a new `session_id`. + * **Every later result** : keeps counting from that reset. + * **The last result before each`/clear`**: holds the total for the turns since the previous reset. + +To total the whole call, add the last result from before each `/clear` to the call’s final result. Every other result, including the `/clear` turn’s own, is superseded by a later one. In TypeScript, the SDK also emits an [`SDKConversationResetMessage`](</docs/en/agent-sdk/typescript#sdkconversationresetmessage>) at each reset, so you can detect resets from the stream. The Python SDK drops that message before it reaches your app, so in Python, count the resets yourself from the `/clear` turns your app sends. `maxBudgetUsd`, or `max_budget_usd` in Python, is compared against the same running total, so a `/clear` also starts the budget over. ## @@ -45,7 +64,7 @@ Get the total cost of a query -The result message ([TypeScript](</docs/en/agent-sdk/typescript#sdkresultmessage>), [Python](</docs/en/agent-sdk/python#resultmessage>)) marks the end of the agent loop for a `query()` call. It includes `total_cost_usd`, the cumulative estimated cost across all steps in that call. This works for both success and error results, though in Python the field is typed as optional and may be `None` on some error paths. If you use sessions to make multiple `query()` calls, each result only reflects the cost of that individual call. The three result-level fields differ in what they count when the agent spawns [subagents](</docs/en/agent-sdk/subagents>). Use `modelUsage`, or `model_usage` in Python, for whole-tree token accounting; the `usage` field undercounts as soon as nesting occurs. +The result message, typed as [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) in TypeScript and [`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>) in Python, marks the end of the agent loop for a `query()` call. It includes `total_cost_usd`, the cumulative estimated cost across all steps in that call. In Python the field is typed as optional, so check that it isn’t `None` before you read it. Success and error results both carry it, though the final result of a session crash may carry it zeroed. If you use sessions to make multiple `query()` calls, each result reflects only the cost of that individual call. In streaming input mode, read call totals as described in Track costs in streaming input mode. The three result-level fields differ in what they count when the agent spawns [subagents](</docs/en/agent-sdk/subagents>). Use `modelUsage`, or `model_usage` in Python, for whole-tree token accounting; the `usage` field undercounts as soon as nesting occurs. Field| Subagent activity ---|--- @@ -107,38 +126,42 @@ Each assistant message contains a nested `BetaMessage` (accessed via `message.message`) with an `id` and `usage` object with token counts. When Claude uses tools in parallel, multiple messages share the same `id` with identical usage data. Track which IDs you’ve already counted and skip duplicates to avoid inflated totals. -Parallel tool calls produce multiple assistant messages whose nested `BetaMessage` shares the same `id` and identical usage. Always deduplicate by ID to get accurate per-step token counts. - -The following example accumulates input and output tokens across all steps, counting each unique message ID only once: +The deduplicated per-step values are accurate for input and cache tokens. Per-step `output_tokens` is a placeholder, so read output tokens from the result message. + +The following example accumulates input tokens across all steps, counting each unique main-loop message ID only once and skipping subagent messages, and reads the output total from the result message, which covers the main loop: import { query } from "@anthropic-ai/claude-agent-sdk"; const seenIds = new Set<string>(); let totalInputTokens = 0; - let totalOutputTokens = 0; + let resultOutputTokens = 0; try { for await (const message of query({ prompt: "Summarize this project" })) { - if (message.type === "assistant") { + if (message.type === "assistant" && !message.parent_tool_use_id) { const msgId = message.message.id; // Parallel tool calls share the same ID, only count once if (!seenIds.has(msgId)) { seenIds.add(msgId); totalInputTokens += message.message.usage.input_tokens; - totalOutputTokens += message.message.usage.output_tokens; } + } + if (message.type === "result") { + // Per-step output_tokens is a placeholder; the result message + // carries the accumulated output total. + resultOutputTokens = message.usage.output_tokens; } } } catch (error) { // A single-shot query() throws after yielding an error result, so the - // totals below still reflect the steps that ran before the failure. + // input total below still reflects the steps that ran before the failure. console.error(`Session ended with an error: ${error}`); } console.log(`Steps: ${seenIds.size}`); console.log(`Input tokens: ${totalInputTokens}`); - console.log(`Output tokens: ${totalOutputTokens}`); + console.log(`Output tokens: ${resultOutputTokens}`); ### @@ -175,7 +198,7 @@ Accumulate costs across multiple calls -Each `query()` call returns its own `total_cost_usd`. The SDK does not provide a session-level total, so if your application makes multiple `query()` calls (for example, in a multi-turn session or across different users), accumulate the totals yourself. The following examples run two `query()` calls sequentially, add each call’s `total_cost_usd` to a running total, and print both the per-call and combined cost: +Each `query()` call returns its own `total_cost_usd`. The SDK doesn’t provide a session-level total, so if your application makes multiple `query()` calls, for example in a multi-turn session or across different users, accumulate the totals yourself. In streaming input mode, read each call’s total as described in Track costs in streaming input mode. For a call that ended in a crash, see Recover totals after a session crash. The following examples run two `query()` calls sequentially, add each call’s `total_cost_usd` to a running total, and print both the per-call and combined cost: TypeScript @@ -244,21 +267,17 @@ ​ -Handle errors, caching, and token discrepancies - -For accurate cost tracking, account for failed conversations, cache token pricing, and occasional reporting inconsistencies. - -### - -​ - -Resolve output token discrepancies - -In rare cases, you might observe different `output_tokens` values for messages with the same ID. When this occurs: - - 1. **Use the highest value:** the final message in a group typically contains the accurate total. - 2. **Prefer the result message:** the `total_cost_usd` in the result message reflects the SDK’s accumulated estimate across all steps, so it is more reliable than summing per-step values yourself. It is still an estimate and may differ from your actual bill. - 3. **Report inconsistencies:** file issues at the [Claude Code GitHub repository](<https://github.com/anthropics/claude-code/issues>). +Handle errors, caching, and output token counts + +For accurate cost tracking, account for the placeholder output count on assistant messages, the tokens a failed conversation consumed, and cache token pricing. + +### + +​ + +Read output tokens from the result message + +Claude Code builds each assistant message from the usage the API reported when the response began, so the message’s `output_tokens` is only the count the API had reported at `message_start`, before the response was generated. One API response can produce several assistant messages, and every one of them carries that same placeholder. The API reports the real output count at the end of the response, and Claude Code adds it to the result message. Read output tokens from the result’s `usage`, or from `modelUsage` for a per-model breakdown. To watch a response’s output count grow while it streams, set `includePartialMessages`, or `include_partial_messages` in Python, and read `usage` from each `message_delta` stream event, typed as [`SDKPartialAssistantMessage`](</docs/en/agent-sdk/typescript#sdkpartialassistantmessage>) in TypeScript and [`StreamEvent`](</docs/en/agent-sdk/python#streamevent>) in Python. ### @@ -266,7 +285,26 @@ Track costs on failed conversations -Both success and error result messages include `usage` and `total_cost_usd`; in Python both fields are typed as optional and may be `None` on some error paths. If a conversation fails mid-way, you still consumed tokens up to the point of failure. Always read cost data from the result message regardless of its `subtype`. +Both success and error result messages include `usage` and `total_cost_usd`; in Python both fields are typed as optional, so check that they aren’t `None` before you read them. If a conversation fails midway, you still consumed tokens up to the point of failure. Read cost data from every result message, whether its `subtype` is `success` or one of the error subtypes. On some error results, `usage` reports less than the call spent: + + * **`error_during_execution` after a session crash**: every cost field may be zeroed. + * **`error_max_budget_usd`** : `usage` leaves out the response that crossed the budget, while `total_cost_usd` and `modelUsage` include it. + +Where you have the choice, account from `total_cost_usd` or `modelUsage` rather than `usage`. + +### + +​ + +Recover totals after a session crash + +When the Claude Code process crashes, it emits a final `error_during_execution` result and exits, in single-shot and streaming input mode alike. That result may carry zeroed `usage`, `total_cost_usd`, and `modelUsage`, so recover the call’s totals from what arrived before it. Step 1 recovers the full totals whenever an earlier result exists; the fallback in step 2 recovers only the main loop’s input and cache tokens. + + 1. Use the result of the turn before the crash. In streaming input mode, it holds the running total since the start of the call or since the last `/clear`. Go to step 2 instead when that result can’t help you: + * The call was single-shot, so no earlier result exists. + * The crash happened on the first turn. + * The turn before the crash was the `/clear` itself, so its result covers only the reset. + 2. Sum the `usage` on the assistant messages instead, counting each API response once, as the Track per-step usage example does. In single-shot mode, sum all of them; in streaming input mode, sum the ones that arrived after the last result. This gives you the main loop’s input and cache tokens. Subagent usage isn’t recoverable this way, and neither are output tokens or USD cost, because per-step `output_tokens` is a placeholder. ###
modified Manage costs effectively View current →
--- a/costs.md +++ b/costs.md @@ -45,6 +45,14 @@ 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. + +### + +​ + +Analyze your usage patterns + +Run [`/insights`](</docs/en/commands#all-commands>) for a report on how you work rather than how many tokens you’ve used. It analyzes your recent sessions on this machine and writes an HTML report covering what you work on, friction points such as misunderstood requests or buggy code, and suggestions for using Claude Code more effectively. A single run analyzes up to 200 sessions it hasn’t seen before and skips very short ones. When sessions are left out, the report header shows the analyzed count with the total in parentheses, for example `200 sessions (412 total)`. Claude Code writes the latest report to `~/.claude/usage-data/report.html` and saves a timestamped copy of each run in the same directory, so earlier reports aren’t overwritten. Claude Code deletes reports on the same schedule as the rest of your session data: at startup, it removes files older than [`cleanupPeriodDays`](</docs/en/claude-directory#cleaned-up-automatically>), 30 days by default. You can run `/insights` on any plan and with any provider. The analysis runs through the same provider and account as your regular sessions, and the tokens count against your plan or API usage. Sessions from other devices and claude.ai aren’t included. ### @@ -144,10 +152,11 @@ When a developer asks about a limit -Developers usually bring limit questions to their admin, so it helps to know which ceiling they hit. The three situations mean different things: +Developers usually bring limit questions to their admin, so it helps to know which ceiling they hit. The four situations mean different things: * **“You’ve hit your session limit” or “You’ve hit your weekly limit”** : a seat-based usage window on a subscription plan. These windows are shared across all models, so switching models with `/model` doesn’t restore access, though it does keep the developer working after the model-specific “You’ve hit your Opus limit” message. The message shows when the window resets, and the developer can run `/usage-credits` to request usage beyond the allowance if you have [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) turned on. See [usage limit errors](</docs/en/errors#youve-hit-your-session-limit>). - * **A context or auto-compact warning** : not a usage limit. The conversation has grown close to the session’s [auto-compact window](</docs/en/context-window#when-your-context-fills-up>), the threshold where Claude Code summarizes older history to free space. Point the developer at reduce token usage. + * **A spend limit message from a[Claude apps gateway](</docs/en/claude-apps-gateway>)**: the developer passed a spend cap you set on your self-hosted gateway, and the gateway blocks their requests until the period resets or you raise the cap. See [gateway spend limits](</docs/en/claude-apps-gateway-spend-limits>) for caps, reset schedules, and the message the developer sees. + * **A context or auto-compact warning** : not a usage limit. The conversation has grown close to the session’s [auto-compact window](</docs/en/model-config#set-the-auto-compact-window>), the threshold where Claude Code summarizes older history to free space. Point the developer at reduce token usage. * **Unexpectedly high spend on an API or cloud-provider plan** : usually traces back to long sessions that were never cleared or to Opus left as the default model. The highest-impact habits to share are clearing between unrelated tasks and matching the model to the job, both covered in reduce token usage. ###
modified Message your other Claude Code sessions View current →
--- a/cross-session-messaging.md +++ b/cross-session-messaging.md @@ -63,7 +63,7 @@ * **Subagents** : agents running inside the current session. [Agent team](</docs/en/agent-teams>) teammates aren’t listed; Claude messages them through the team’s own roster. * **Your other local sessions** : Claude Code sessions running on the same machine, including [background sessions](</docs/en/agent-view>). A session appears only when it binds an inbox socket. - * **Your cloud sessions** : your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions. These appear when this session has cloud access: a claude.ai login on the first-party Anthropic API and an organization policy that allows cloud sessions. + * **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>). * **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 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. An interactive session gets a name derived from its working directory’s folder name, such as `myapp-3f`. Two sessions can end up with the same name. The `/list-agents` output shows each local session’s working directory, which tells same-named sessions apart when they run in different directories. Claude’s own listing adds a short identifier to each row and uses it in the address when names collide. @@ -130,7 +130,7 @@ * **Approve** delivers that one message to Claude. * **Deny** , or dismissing the dialog, drops it. - * Left unanswered past the [`dialogExpiry`](</docs/en/settings#available-settings>) deadline, the dialog closes and Claude Code drops the message. The deadline defaults to five minutes. + * When the dialog stays unanswered past the [`dialogExpiry`](</docs/en/settings#available-settings>) deadline, Claude Code closes it and drops the message. The deadline defaults to five minutes. While no terminal is attached to a [background session](</docs/en/agent-view>), Claude Code leaves the dialog open past the deadline. After you attach, Claude Code closes the dialog and drops the message only if it stays unanswered for a full deadline period. * If this session’s permission-mode class changes while messages are held, Claude Code re-applies the inbound rules, delivers the messages they now accept, and shows a notice. * If a change makes `refuse` apply while messages are held, Claude Code drops every held message and reports a denial to each sender it can reach. @@ -142,7 +142,12 @@ Non-interactive sessions -Claude Code binds an inbox socket for a [`claude -p`](</docs/en/headless>) session like an interactive one, so a long-running `-p` worker can receive messages and appears in the listing. When you start a session in [bare mode](</docs/en/headless#start-faster-with-bare-mode>), Claude Code doesn’t bind the socket, so that session can’t receive messages and doesn’t appear in the agent list. A `-p` session can’t show the approval dialog. When the inbound default holds a message there, Claude Code delivers it if a later mode or settings change allows it, and otherwise drops it when the [`dialogExpiry`](</docs/en/settings#available-settings>) deadline passes and reports the expiry to the sender. Before v2.1.225, a held message stayed held in a `-p` session, with no sender notice and no expiry. To let a `-p` worker take messages unattended, start it with `crossSessionInbound` set to `accept` in its `--settings` value. An `accept` in your user settings also works but applies to every session you run. +Claude Code binds an inbox socket for a [`claude -p`](</docs/en/headless>) session like an interactive one, so a long-running `-p` worker can receive messages and appears in the listing. When you start a session in [bare mode](</docs/en/headless#start-faster-with-bare-mode>), Claude Code doesn’t bind the socket, so that session can’t receive messages and doesn’t appear in the agent list. A `-p` session can’t show the approval dialog. When the inbound default holds a message there, Claude Code keeps it for the same [`dialogExpiry`](</docs/en/settings#available-settings>) deadline the dialog uses, five minutes by default: + + * **Before the deadline** : if a mode or settings change allows the message, Claude Code delivers it. + * **Past the deadline** : Claude Code drops the message and reports it as expired to a sender it can reach. + +Set `dialogExpiry` to `"never"` to keep default-held messages until the session ends. A message held by an explicit `hold` setting doesn’t expire; Claude Code delivers it only when an `accept` later applies. When the session ends with messages still held, Claude Code reports them as expired to each sender it can reach. Before v2.1.225, no deadline applied in a `-p` session: a held message stayed held unless a permission-mode change during the run delivered it, and a session that ended with held messages reported nothing to their senders. To let a `-p` worker take messages unattended, start it with `crossSessionInbound` set to `accept` in its `--settings` value. An `accept` in your user settings also works but applies to every session you run. ### @@ -180,7 +185,7 @@ "isolatePeerMachines": true } -With this set, Claude Code asks for your approval before Claude’s message to a session beyond this machine leaves, even in `bypassPermissions` mode, which skips ordinary permission prompts. A `true` from any settings scope applies, so a checked-in project file can turn the requirement on but not off. Messages between sessions on the same machine don’t prompt. +With this set, Claude Code asks for your approval before Claude’s message to a session beyond this machine leaves, even in `bypassPermissions` mode, which skips ordinary permission prompts. A `true` from any settings scope applies, so a checked-in project file can turn the requirement on but not off. Claude Code doesn’t prompt for messages between sessions on the same machine. ### @@ -222,7 +227,7 @@ * **`/list-agents` works but a send didn’t arrive**: messaging is on, and something narrower applies: * **Deny rules** : a permission deny rule removes the `SendMessage` and `ListAgents` tools. * **Inbound controls** : the receiving session’s inbound controls can hold or drop what you send it. - * **Cloud session missing** : a cloud session appears only when this session has cloud access. + * **Cloud session missing** : a cloud session appears only while this session is connected to [Remote Control](</docs/en/remote-control>). * **Other-machine session missing** : a session on another of your machines appears only when it runs with [Remote Control](</docs/en/remote-control>) and this session is connected as well. * **Starting a conversation** : Message sessions on other machines covers starting a conversation with a session beyond this machine.
modified Give Claude custom tools View current →
--- a/custom-tools.md +++ b/custom-tools.md @@ -313,18 +313,7 @@ Control tool access -The weather tool example registered a server and listed tools in `allowedTools`. This section covers how tool names are constructed and how to scope access when you have multiple tools or want to restrict built-ins. - -### - -​ - -Tool name format - -When MCP tools are exposed to Claude, their names follow a specific format: - - * Pattern: `mcp__{server_name}__{tool_name}` - * Example: A tool named `get_temperature` in server `weather` becomes `mcp__weather__get_temperature` +The weather tool example registered a server and listed tools in `allowedTools`. This section covers how to scope access when you have multiple tools or want to restrict built-ins. For how tool names are constructed, see Call a custom tool. ### @@ -853,7 +842,7 @@ Next steps -Custom tools wrap async functions in a standard interface. You can mix the patterns on this page in the same server: a single server can hold a database tool, an API gateway tool, and an image renderer alongside each other. From here: +You can mix the patterns on this page in the same server: a single server can hold a database tool, an API gateway tool, and an image renderer alongside each other. From here: * If your server grows to dozens of tools, see [tool search](</docs/en/agent-sdk/tool-search>) to defer loading them until Claude needs them. * To connect to external MCP servers (filesystem, GitHub, Slack) instead of building your own, see [Connect MCP servers](</docs/en/agent-sdk/mcp>).
modified Desktop application View current →
--- a/desktop.md +++ b/desktop.md @@ -34,7 +34,7 @@ Before you send your first message, configure four things in the prompt area: - * **Environment** : choose where Claude runs. Select **Local** for your machine, **Cloud** for cloud sessions, an **SSH connection** for a remote machine you manage, or on Windows a [**WSL distribution**](</docs/en/desktop-wsl>). See environment configuration. + * **Environment** : choose where Claude runs. Select **Local** for your machine, **Cloud** for a cloud session that continues after you close the app, an **SSH connection** for a remote machine you manage, or on Windows a [**WSL distribution**](</docs/en/desktop-wsl>). See environment configuration. * **Project folder** : select the folder or repository Claude works in. For cloud sessions, you can add multiple repositories. * **Model** : pick a [model](</docs/en/model-config#available-models>) from the dropdown next to the send button. You can change this during the session. * **Permission mode** : choose how much autonomy Claude has from the mode selector. You can change this during the session. @@ -88,7 +88,7 @@ Start complex tasks in Plan so Claude maps out an approach before making changes. Once you approve the plan, switch to Accept edits or Manual to execute it. See [explore first, then plan, then code](</docs/en/best-practices#explore-first-then-plan-then-code>) for more on this workflow. -Cloud sessions support Accept edits, Plan, and Auto. Accept edits corresponds to `default` mode: cloud sessions pre-approve file edits, so the selector shows Accept edits instead of Manual. Bypass permissions is not available in cloud sessions. Enterprise admins can restrict which permission modes are available. See enterprise configuration for details. +Cloud sessions support Accept edits, Plan, and Auto. Accept edits corresponds to `default` mode: cloud sessions pre-approve file edits, so the selector shows Accept edits instead of Manual. Bypass permissions isn’t available in cloud sessions, including sessions in a [self-hosted environment](</docs/en/self-hosted-environments>). Enterprise admins can restrict which permission modes are available. See enterprise configuration for details. ### @@ -425,7 +425,7 @@ Sessions from Dispatch -[Dispatch](<https://support.claude.com/en/articles/13947068>) is a persistent conversation with Claude that lives in the [Cowork](<https://claude.com/product/cowork>) tab. You message Dispatch a task, and it decides how to handle it. A task can end up as a Code session in two ways: you ask for one directly, such as “open a Claude Code session and fix the login bug”, or Dispatch decides the task is development work and spawns one on its own. Tasks that typically route to Code include fixing bugs, updating dependencies, running tests, or opening pull requests. Research, document editing, and spreadsheet work stay in Cowork. Either way, the Code session appears in the Code tab’s sidebar with a **Dispatch** badge. You get a push notification on your phone when it finishes or needs your approval. If you have computer use enabled, Dispatch-spawned Code sessions can use it too. App approvals in those sessions expire after 30 minutes and re-prompt, rather than lasting the full session like regular Code sessions. For setup, pairing, and Dispatch settings, see the [Dispatch help article](<https://support.claude.com/en/articles/13947068>). Dispatch requires a Pro or Max plan and is not available on Team or Enterprise plans. Dispatch is one of several ways to work with Claude when you’re away from your terminal. See [Platforms and integrations](</docs/en/platforms#work-when-you-are-away-from-your-terminal>) to compare it with Remote Control, Channels, Slack, and scheduled tasks. +[Dispatch](<https://support.claude.com/en/articles/13947068>) is a persistent conversation with Claude that lives in the [Cowork](<https://claude.com/product/cowork>) tab. You message Dispatch a task, and it decides how to handle it. A task can end up as a Code session in two ways: you ask for one directly, such as “open a Claude Code session and fix the login bug”, or Dispatch decides the task is development work and spawns one on its own. Tasks that typically route to Code include fixing bugs, updating dependencies, running tests, or opening pull requests. Research, document editing, and spreadsheet work stay in Cowork. Either way, the Code session appears in the Code tab’s sidebar with a **Dispatch** badge. You get a push notification on your phone when it finishes or needs your approval. If you have computer use enabled, Dispatch-spawned Code sessions can use it too. App approvals in those sessions expire after 30 minutes and re-prompt, rather than lasting the full session like regular Code sessions. For setup, pairing, and Dispatch settings, see the [Dispatch help article](<https://support.claude.com/en/articles/13947068>). Dispatch requires a Pro or Max plan and is not available on Team or Enterprise plans. Dispatch is one of several ways to work with Claude when you’re away from your terminal. For a comparison with the other options, see [Platforms and integrations](</docs/en/platforms#work-when-you-are-away-from-your-terminal>). ## @@ -835,7 +835,7 @@ Data handling -Claude Code processes your code locally in local sessions, or in cloud sessions on Anthropic-managed infrastructure, unless your organization routes them to a [self-hosted environment](</docs/en/self-hosted-environments>). Conversations and code context are sent to Anthropic’s API for processing. See [data handling](</docs/en/data-usage>) for details on data retention, privacy, and compliance. +Claude Code processes your code locally in local sessions, or in cloud sessions on Anthropic-managed infrastructure, unless your organization routes them to a [self-hosted environment](</docs/en/self-hosted-environments>). Cloud sessions, including in a self-hosted environment, send conversations and code context to Anthropic’s API for processing; local and SSH sessions send them to whichever model provider your deployment configures, Anthropic’s API by default. See [data handling](</docs/en/data-usage>) for details on data retention, privacy, and compliance. ###
modified Test iOS apps in the simulator View current →
--- a/desktop-ios-simulator.md +++ b/desktop-ios-simulator.md @@ -1,4 +1,4 @@ -The iOS Simulator pane is in public beta in Claude Code Desktop on macOS. It’s available on Pro, Max, Team, and Enterprise plans. +The iOS Simulator pane is in public beta in Claude Code Desktop on macOS. It’s available on Pro, Max, Team, and Enterprise plans, except in Enterprise organizations that have a HIPAA configuration or [Zero Data Retention (ZDR)](</docs/en/zero-data-retention>) enabled. The iOS Simulator pane shows your app running in Apple’s iOS Simulator next to your conversation in Claude Code Desktop. When Claude builds, installs, launches, or checks your app in a simulator, the pane opens automatically and streams the device screen live. Use it to watch Claude run and test your app, or to tap through the app yourself while Claude keeps working. The simulator pane drives the simulator directly, so it doesn’t need [computer use](</docs/en/desktop#let-claude-use-your-computer>) and never takes over your screen or hides your other windows. From the CLI, Claude reaches the iOS Simulator through [computer use](</docs/en/computer-use#test-a-simulator-flow>) instead, which controls the simulator on your screen the same way you would with a mouse. @@ -139,6 +139,7 @@ * State the goal explicitly, for example “run the app in the iOS Simulator and tap through the signup flow”. * Confirm Xcode and the iOS simulators are installed and that your Xcode version meets the requirements. * If your organization manages Claude Code, the simulator tools may be disabled by policy. + * If you’re in an Enterprise organization that has a HIPAA configuration or ZDR enabled, the simulator pane isn’t available to you. * The simulator pane requires Claude Desktop v1.24012.0 or later. Open **Claude → Check for Updates** , then restart the app. ###
modified Claude Desktop on Linux (beta) View current →
--- a/desktop-linux.md +++ b/desktop-linux.md @@ -1,6 +1,6 @@ -Linux support for the Claude desktop app is in beta. The Chat, Cowork, and Code tabs are all available. +Linux support for the Claude desktop app is in beta. -The desktop app on Linux gives you the same Chat, Cowork, and Claude Code experience as macOS and Windows: parallel sessions, visual diff review, an integrated terminal and editor, and live app preview. See [Use Claude Code Desktop](</docs/en/desktop>) for the full feature reference. +The desktop app on Linux gives you the same Chat, Cowork, and Claude Code experience as on macOS and Windows: parallel sessions, visual diff review, an integrated terminal and editor, and live app preview. See [Use Claude Code Desktop](</docs/en/desktop>) for the feature reference. ##
modified Environment variables View current →
Show diff (146 lines)
--- a/env-vars.md +++ b/env-vars.md @@ -123,7 +123,7 @@ `ANTHROPIC_BEDROCK_REGION_PREFIX`| Cross-region inference profile prefix (`us`, `eu`, `apac`, `jp`, `au`, or `global`) Claude Code tries first instead of the one derived from the AWS region. Ignored in AWS GovCloud regions. Requires Claude Code v2.1.224 or later. See [Amazon Bedrock](</docs/en/amazon-bedrock#cross-region-inference-profile-prefixes>) `ANTHROPIC_BEDROCK_SERVICE_TIER`| Amazon Bedrock [service tier](<https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html>) (`default`, `flex`, or `priority`). Sent as the `X-Amzn-Bedrock-Service-Tier` header. See [Amazon Bedrock](</docs/en/amazon-bedrock#service-tiers>) `ANTHROPIC_BETAS`| Comma-separated list of additional `anthropic-beta` header values to include in API requests. Claude Code already sends the beta headers it needs; use this to opt into an [Anthropic API beta](<https://platform.claude.com/docs/en/api/beta-headers>) before Claude Code adds native support. Unlike the [`--betas` flag](</docs/en/cli-reference#cli-flags>), which requires API key authentication, this variable works with all auth methods including Claude.ai subscription -`ANTHROPIC_CUSTOM_HEADERS`| Custom headers to add to requests (`Name: Value` format, newline-separated for multiple headers) +`ANTHROPIC_CUSTOM_HEADERS`| Custom headers to add to requests (`Name: Value` format, newline-separated for multiple headers). If a name or value contains a character an HTTP header can’t carry, such as a curly quote or a zero-width space, Claude Code fails the request with an error that identifies the pair by position. Requires Claude Code v2.1.227 or later. [Invalid request header value](</docs/en/errors#invalid-request-header-value>) lists the exact character set and where the check runs `ANTHROPIC_CUSTOM_MODEL_OPTION`| Model ID to add as a custom entry in the `/model` picker. Use this to make a non-standard or gateway-specific model selectable without replacing built-in aliases. See [Model configuration](</docs/en/model-config#add-a-custom-model-option>) `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION`| Display description for the custom model entry in the `/model` picker. Defaults to `Custom model (<model-id>)` when not set `ANTHROPIC_CUSTOM_MODEL_OPTION_NAME`| Display name for the custom model entry in the `/model` picker. Defaults to the model ID when not set @@ -144,11 +144,14 @@ `ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION`| Display description for the pinned Sonnet model in the `/model` picker. When not set, defaults to `Custom Sonnet model`, or `Custom Sonnet model (1M context)` if the pinned model ID has the `[1m]` suffix and `CLAUDE_CODE_DISABLE_1M_CONTEXT` isn’t turned on. See [Model configuration](</docs/en/model-config#customize-pinned-model-display-and-capabilities>) `ANTHROPIC_DEFAULT_SONNET_MODEL_NAME`| Display name for the pinned Sonnet model in the `/model` picker. Defaults to the model ID when not set. See [Model configuration](</docs/en/model-config#customize-pinned-model-display-and-capabilities>) `ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES`| Comma-separated list of [capabilities](</docs/en/model-config#customize-pinned-model-display-and-capabilities>) the pinned Sonnet model supports, for example `effort,thinking`. See [Model configuration](</docs/en/model-config#customize-pinned-model-display-and-capabilities>) +`ANTHROPIC_FEDERATION_RULE_ID`| Federation rule ID for [Workload Identity Federation](<https://platform.claude.com/docs/en/manage-claude/workload-identity-federation>). When you set it together with `ANTHROPIC_ORGANIZATION_ID`, Claude Code selects federation credentials, which rank above your `/login` credential. See [authentication precedence](</docs/en/authentication#authentication-precedence>) `ANTHROPIC_FOUNDRY_API_KEY`| API key for Microsoft Foundry authentication (see [Microsoft Foundry](</docs/en/microsoft-foundry>)) `ANTHROPIC_FOUNDRY_AUTH_TOKEN`| Bearer token for Microsoft Foundry authentication, such as a Microsoft Entra access token. Claude Code sends it as the `Authorization: Bearer` header. Takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` and over the Azure default credential chain. See [Microsoft Foundry](</docs/en/microsoft-foundry>). Requires Claude Code v2.1.203 or later `ANTHROPIC_FOUNDRY_BASE_URL`| Full base URL for the Microsoft Foundry resource (for example, `https://my-resource.services.ai.azure.com/anthropic`). Alternative to `ANTHROPIC_FOUNDRY_RESOURCE` (see [Microsoft Foundry](</docs/en/microsoft-foundry>)) `ANTHROPIC_FOUNDRY_RESOURCE`| Microsoft Foundry resource name (for example, `my-resource`). Required if `ANTHROPIC_FOUNDRY_BASE_URL` is not set (see [Microsoft Foundry](</docs/en/microsoft-foundry>)) `ANTHROPIC_MODEL`| Name of the model setting to use (see [Model Configuration](</docs/en/model-config#environment-variables>)) +`ANTHROPIC_ORGANIZATION_ID`| Organization ID for [Workload Identity Federation](<https://platform.claude.com/docs/en/manage-claude/workload-identity-federation>). Set it together with `ANTHROPIC_FEDERATION_RULE_ID`. See [authentication precedence](</docs/en/authentication#authentication-precedence>) +`ANTHROPIC_PROFILE`| Name of the Anthropic profile to authenticate with, such as one created by [`ant auth login`](<https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication>). The named profile ranks above your `/login` credential. See [authentication precedence](</docs/en/authentication#authentication-precedence>) `ANTHROPIC_SMALL_FAST_MODEL`| [DEPRECATED] Name of [Haiku-class model for background tasks](</docs/en/costs>) `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION`| Override AWS region for the Haiku-class model when using Amazon Bedrock or Amazon Bedrock Mantle. On Amazon Bedrock, this only takes effect when `ANTHROPIC_DEFAULT_HAIKU_MODEL` or the deprecated `ANTHROPIC_SMALL_FAST_MODEL` is also set, since Amazon Bedrock otherwise runs background tasks on the [default Sonnet model or the primary model](</docs/en/amazon-bedrock#4-pin-model-versions>) in the session region `ANTHROPIC_VERTEX_BASE_URL`| Override Google Cloud’s Agent Platform endpoint URL. Use for custom Google Cloud’s Agent Platform endpoints or when routing through an [LLM gateway](</docs/en/llm-gateway>). See [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>) @@ -167,9 +170,10 @@ `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS`| Set to `1` to disable all built-in [subagent](</docs/en/sub-agents>) types such as Explore and Plan. Only applies in non-interactive mode (the `-p` flag). Useful for SDK users who want a blank slate `CLAUDE_AGENT_SDK_MCP_NO_PREFIX`| Set to `1` to skip the `mcp__<server>__` prefix on tool names from SDK-created MCP servers. Tools use their original names. SDK usage only `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`| Stall timeout in milliseconds for background subagents. Default `600000` (10 minutes). The timer resets on each streaming progress event; if no progress arrives within the window, the subagent is aborted and the task is marked failed, surfacing any partial result to the parent -`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`| Set the percentage (1-100) of the auto-compact window at which auto-compaction triggers. Use lower values like `50` to compact earlier; the variable can’t raise the threshold, so values above the default percentage are ignored. It applies only in sessions that [compact before the model’s context limit](</docs/en/context-window#set-the-auto-compact-window>). Applies to both main conversations and subagents +`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`| Set the percentage (1-100) of the auto-compact window at which auto-compaction triggers. Use lower values like `50` to compact earlier; the variable can’t raise the threshold, so values above the default percentage are ignored. It applies only in sessions that [compact before the model’s context limit](</docs/en/model-config#context-window-and-auto-compaction>). Applies to both main conversations and subagents `CLAUDE_AUTO_BACKGROUND_TASKS`| Set to `1` to force-enable automatic backgrounding of long-running agent tasks. When enabled, subagents are moved to the background after running for approximately two minutes. Also enables [automatic backgrounding of long MCP tool calls](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>) in non-interactive mode on Claude Code v2.1.212 or later `CLAUDE_AX_SCREEN_READER`| Set to `1` to render screen-reader friendly output: flat text without decorative borders or animations. Set to `0` to force screen-reader mode off even when [`axScreenReader`](</docs/en/settings#available-settings>) is `true`. The [`--ax-screen-reader`](</docs/en/cli-reference#cli-flags>) flag takes precedence. Requires Claude Code v2.1.181 or later +`CLAUDE_AX_STARTUP_QUIET_MS`| In [screen reader mode](</docs/en/accessibility>), how many milliseconds Claude Code holds the first interface render after the startup confirmation line, so your screen reader can speak the line in full before new output interrupts it. Default `3000`. Set `0` to render immediately. Claude Code caps the hold at `600000` (10 minutes). Your first keystroke ends the hold early. Requires Claude Code v2.1.217 or later `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR`| Return to the original working directory after each Bash or PowerShell command in the main session `CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS`| Timeout in milliseconds for the byte-level streaming idle watchdog only; when set, it takes precedence over `CLAUDE_STREAM_IDLE_TIMEOUT_MS` for that watchdog and leaves the event-level watchdog unchanged. Claude Code clamps this variable to between 10 seconds and 30 minutes. Requires Claude Code v2.1.210 or later `CLAUDE_CLIENT_PRESENCE_FILE`| Path to a file that an external tool, such as a screen-lock listener, creates when you unlock your screen and deletes when you lock it. While the file exists, Claude Code skips [Remote Control mobile push notifications](</docs/en/remote-control#mobile-push-notifications>), so you stop getting pushes while you are actively using the computer. When the file is absent or unreadable, notifications are sent as normal. Claude Code checks the file once per push-triggering event rather than polling it. Requires Claude Code v2.1.181 or later @@ -180,7 +184,7 @@ `CLAUDE_CODE_API_KEY_HELPER_TTL_MS`| Interval in milliseconds at which credentials should be refreshed (when using [`apiKeyHelper`](</docs/en/settings#available-settings>)) `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_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. 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](</docs/en/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/context-window#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_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#global-config-settings>) global config setting `CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS`| Time in milliseconds Claude Code waits for the AWS default credential provider chain to produce credentials before the request fails with [`AWS default-chain credential resolve timed out`](</docs/en/errors#aws-default-chain-credential-resolve-timed-out>) (default: `60000`). Raise it when a step in your chain legitimately needs longer, such as a browser-based SSO sign-in with MFA through a wrapper like `aws-vault`. Applies wherever Claude Code signs with the default chain: [Amazon Bedrock](</docs/en/amazon-bedrock#credential-caching-and-resolution-timeout>), [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), and the [Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>). Requires Claude Code v2.1.207 or later `CLAUDE_CODE_BRIDGE_SESSION_ID`| Set automatically in Bash tool and [hook command](</docs/en/hooks>) subprocesses while the session has an active [Remote Control](</docs/en/remote-control>) connection, and removed when the connection ends. The value is the session’s ID in `session_` form, the same identifier that appears in the session’s `claude.ai/code` URL, so a script can link back to the session that ran it. Requires Claude Code v2.1.199 or later. In [cloud sessions](</docs/en/claude-code-on-the-web>), read `CLAUDE_CODE_REMOTE_SESSION_ID` instead @@ -192,7 +196,7 @@ `CLAUDE_CODE_CONNECT_TIMEOUT_MS`| Removed in v2.1.186 and now a no-op. Previously set a separate timeout for the connect, TLS, and response-header phase of a streaming API request. Use `API_TIMEOUT_MS` for the per-request timeout `CLAUDE_CODE_DEBUG_LOGS_DIR`| Override the debug log file path. Despite the name, this is a file path, not a directory. Requires debug mode to be enabled separately via `--debug`, `/debug`, or the `DEBUG` environment variable: setting this variable alone does not enable logging. The [`--debug-file`](</docs/en/cli-reference#cli-flags>) flag does both at once. Defaults to `~/.claude/debug/<session-id>.txt` `CLAUDE_CODE_DEBUG_LOG_LEVEL`| Minimum log level written to the debug log file. Values: `verbose`, `debug` (default), `info`, `warn`, `error`. Set to `verbose` to include high-volume diagnostics like full status line command output, or raise to `error` to reduce noise -`CLAUDE_CODE_DISABLE_1M_CONTEXT`| Set to `1` to disable [1M context window](</docs/en/model-config#extended-context>) support. When set, 1M model variants are unavailable in the model picker, and [Sonnet 5](</docs/en/model-config#sonnet-5-context-window>) sessions are treated as having a 200K window. Useful for enterprise environments with compliance requirements +`CLAUDE_CODE_DISABLE_1M_CONTEXT`| Set to `1` to disable [1M context window](</docs/en/model-config#extended-context>) support. When set, 1M model variants are unavailable in the model picker, and Claude Code holds sessions on models with a native 1M window, such as [Sonnet 5](</docs/en/model-config#sonnet-5-context-window>) and Fable 5, to a 200K window; see [Extended context](</docs/en/model-config#extended-context>) for how the hold is enforced. Useful for enterprise environments with compliance requirements. For its role in correcting the window for an unrecognized `[1m]` model ID, see [Correct the window for a gateway or custom model ID](</docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id>) `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING`| Set to `1` to disable [adaptive reasoning](</docs/en/model-config#adjust-effort-level>) on Opus 4.6 and Sonnet 4.6 and fall back to the fixed thinking budget controlled by `MAX_THINKING_TOKENS`. Has no effect on Fable 5, Sonnet 5, or Opus 4.7 and later, which always use adaptive reasoning `CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION`| Set to `1` to stop Claude Code from merging [managed settings](</docs/en/settings#settings-precedence>) `env` blocks per key across admin sources, so only the highest-priority source’s whole `env` block applies, as before v2.1.223. Set it in the environment that launches Claude Code, since Claude Code ignores a copy delivered through a settings `env` block. Requires Claude Code v2.1.223 or later `CLAUDE_CODE_DISABLE_ADVISOR_TOOL`| Set to `1` to disable the [advisor tool](</docs/en/advisor>). The `/advisor` command becomes unavailable, any configured `advisorModel` is ignored, and the `--advisor` flag is accepted but has no effect, so existing scripts that pass it continue to work without errors @@ -208,7 +212,7 @@ `CLAUDE_CODE_DISABLE_BUNDLED_SKILLS`| Set to `1` to disable the [skills](</docs/en/skills>) and workflows included with Claude Code: bundled skills and workflows are removed entirely, while built-in commands like `/init` stay typable but are hidden from the model. `/doctor` stays typable like the built-in commands; hide it with `DISABLE_DOCTOR_COMMAND` instead. Skills from plugins, `.claude/skills/`, and `.claude/commands/` are unaffected. Equivalent to the [`disableBundledSkills`](</docs/en/settings#available-settings>) setting `CLAUDE_CODE_DISABLE_CLAUDE_MDS`| Set to `1` to prevent loading any CLAUDE.md memory files into context, including user, project, and auto-memory files `CLAUDE_CODE_DISABLE_CRON`| Set to `1` to disable [scheduled tasks](</docs/en/scheduled-tasks>). The `/loop` skill and cron tools become unavailable and any already-scheduled tasks stop firing, including tasks that are already running mid-session -`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`| Set to `1` to strip Anthropic-specific `anthropic-beta` request headers and beta tool-schema fields (such as `defer_loading` and `eager_input_streaming`) from API requests. Use this when a proxy gateway rejects requests with errors like “Unexpected value(s) for the `anthropic-beta` header” or “Extra inputs are not permitted”. Standard fields (`name`, `description`, `input_schema`, `cache_control`) are preserved. [MCP tool search](</docs/en/mcp#scale-with-mcp-tool-search>) is disabled and all MCP tools load upfront, even when `ENABLE_TOOL_SEARCH` is set +`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`| Set to `1` to strip Anthropic-specific `anthropic-beta` request headers and beta tool-schema fields (such as `defer_loading` and `eager_input_streaming`) from API requests. Use this when a proxy gateway rejects requests with errors like “Unexpected value(s) for the `anthropic-beta` header” or “Extra inputs are not permitted”. Standard fields (`name`, `description`, `input_schema`, `cache_control`) are preserved. [MCP tool search](</docs/en/mcp#scale-with-mcp-tool-search>) is disabled and all MCP tools load upfront, even when you set `ENABLE_TOOL_SEARCH`. On Claude Code v2.1.227 or later, [managed settings](</docs/en/settings#settings-files>) can keep tool search on. [Disable pre-release capabilities](</docs/en/llm-gateway-protocol#disable-pre-release-capabilities>) covers where the override applies `CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS`| Set to `1` to disable the built-in [Explore and Plan subagents](</docs/en/sub-agents#built-in-subagents>). Claude explores with its search tools or the general-purpose subagent instead, and [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) reads files directly rather than launching Explore and Plan agents. Custom subagents named `Explore` or `Plan` are unaffected. To remove every built-in subagent type in the Agent SDK or non-interactive mode, use `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` instead. Requires Claude Code v2.1.198 or later `CLAUDE_CODE_DISABLE_FAST_MODE`| Set to `1` to disable [fast mode](</docs/en/fast-mode>) `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY`| Set to `1` to disable the “How is Claude doing?” session quality surveys. Surveys are also disabled when `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set, unless `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL` opts back in. To set a sample rate instead of disabling outright, use the [`feedbackSurveyRate`](</docs/en/settings#available-settings>) setting. See [Session quality surveys](</docs/en/data-usage#session-quality-surveys>) @@ -224,6 +228,7 @@ `CLAUDE_CODE_DISABLE_POLICY_SKILLS`| Set to `1` to skip loading skills from the system-wide managed skills directory. Useful for container or CI sessions that should not load operator-provisioned skills `CLAUDE_CODE_DISABLE_TERMINAL_TITLE`| Set to `1` to disable automatic terminal title updates based on conversation context. In Agent SDK and `claude -p` sessions, this also skips the background small/fast-model request that generates the session title `CLAUDE_CODE_DISABLE_THINKING`| Set to `1` to omit the `thinking` parameter from API requests entirely. This is a compatibility option for proxies and gateways that reject the parameter. The variable’s behavior is unchanged from earlier versions; on models that think by default, omitting the parameter means the model may still think. To explicitly disable [extended thinking](<https://platform.claude.com/docs/en/build-with-claude/extended-thinking>) on the Anthropic API, use `MAX_THINKING_TOKENS=0` instead, which is also ineffective on Fable 5 since it cannot have thinking turned off. On [third-party providers](</docs/en/third-party-integrations>), `0` likewise omits the parameter, so the two variables behave the same there +`CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT`| Set to `1` to skip proactive [auto-compaction](</docs/en/costs#reduce-token-usage>) when Claude Code doesn’t recognize the model ID, such as an [LLM gateway](</docs/en/llm-gateway>) alias. Without this variable, Claude Code compacts at the context window it assumes for the ID. `CLAUDE_CODE_MAX_CONTEXT_TOKENS` can correct the assumed window instead; see [Correct the window for a gateway or custom model ID](</docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id>) for when each variable applies. Requires Claude Code v2.1.223 or later `CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL`| Set to `1` to disable virtual scrolling in [fullscreen rendering](</docs/en/fullscreen>) and render every message in the transcript. Use this if scrolling in fullscreen mode shows blank regions where messages should appear `CLAUDE_CODE_DISABLE_WORKFLOWS`| Set to `1` to disable [workflows](</docs/en/workflows#turn-workflows-off>). Equivalent to the [`disableWorkflows`](</docs/en/settings#available-settings>) setting `CLAUDE_CODE_EFFORT_LEVEL`| Set the effort level for supported models. Values: `low`, `medium`, `high`, `xhigh`, `max`, or `auto` to use the model default. Available levels depend on the model. Takes precedence over `/effort` and the `effortLevel` setting. See [Adjust effort level](</docs/en/model-config#adjust-effort-level>) @@ -256,7 +261,7 @@ `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`| Set to `1` to skip auto-installation of IDE extensions. Equivalent to setting [`autoInstallIdeExtension`](</docs/en/settings#global-config-settings>) to `false` `CLAUDE_CODE_IDE_SKIP_VALID_CHECK`| Set to `1` to skip validation of IDE lockfile entries during connection. Use when auto-connect fails to find your IDE despite it running `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS`| How many [subagents](</docs/en/sub-agents#concurrent-subagent-limit>) can be running in one session before the Agent tool refuses to spawn another (default: 20). Accepts a positive whole number in plain digits; anything else is ignored, so the variable can adjust the cap but can’t disable it. Requires Claude Code v2.1.217 or later -`CLAUDE_CODE_MAX_CONTEXT_TOKENS`| Override the context window size Claude Code assumes for the active model. As of v2.1.193, applied directly for model names Claude Code does not recognize as a Claude model; for recognized Claude models it only takes effect when `DISABLE_COMPACT` is also set. Use this when routing to a model through `ANTHROPIC_BASE_URL` whose context window does not match the built-in size for its name +`CLAUDE_CODE_MAX_CONTEXT_TOKENS`| Override the context window size Claude Code assumes for the active model. As of v2.1.193, how it applies depends on how Claude Code resolves the model ID; see [Correct the window for a gateway or custom model ID](</docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id>). Use this when routing to a model through `ANTHROPIC_BASE_URL` whose context window does not match the built-in size for its name `CLAUDE_CODE_MAX_OUTPUT_TOKENS`| Set the maximum number of output tokens for most requests. Defaults and caps vary by model; see [max output tokens](<https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison>). Claude Code defaults to 32000 for model IDs it doesn’t recognize, such as gateway-specific names, and lowers values above a model’s cap to the cap. Increasing this value reduces the effective context window available before [auto-compaction](</docs/en/costs#reduce-token-usage>) triggers `CLAUDE_CODE_MAX_RETRIES`| Override the number of times to retry failed API requests (default: 10). Capped at 15 as of v2.1.186; as of v2.1.199, `CLAUDE_CODE_RETRY_WATCHDOG` raises the default and removes the cap. For unattended sessions that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG` instead `CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION`| Removed in v2.1.224 and now a no-op. Previously capped the total number of [subagents](</docs/en/sub-agents>) Claude could spawn with the Agent tool in one session (default: 200); spawning past the cap failed with `Subagent spawn limit reached`. The [concurrent subagent limit](</docs/en/sub-agents#concurrent-subagent-limit>) and the [depth limit](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>) still apply @@ -273,7 +278,7 @@ `CLAUDE_CODE_NO_FLICKER`| Set to `1` to enable [fullscreen rendering](</docs/en/fullscreen>), a research preview that reduces flicker and keeps memory flat in long conversations. Equivalent to the [`tui`](</docs/en/settings#available-settings>) setting; you can also switch with `/tui fullscreen` `CLAUDE_CODE_OAUTH_REFRESH_TOKEN`| OAuth refresh token for Claude.ai authentication. When set, `claude auth login` exchanges this token directly instead of opening a browser. Requires `CLAUDE_CODE_OAUTH_SCOPES`. Useful for provisioning authentication in automated environments `CLAUDE_CODE_OAUTH_SCOPES`| Space-separated OAuth scopes the refresh token was issued with, such as `"user:profile user:inference user:sessions:claude_code"`. Required when `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` is set -`CLAUDE_CODE_OAUTH_TOKEN`| OAuth access token for Claude.ai authentication. Alternative to `/login` for SDK and automated environments. Takes precedence over keychain-stored credentials. Generate one with [`claude setup-token`](</docs/en/authentication#generate-a-long-lived-token>) +`CLAUDE_CODE_OAUTH_TOKEN`| OAuth access token for Claude.ai authentication. Alternative to `/login` for SDK and automated environments. Takes precedence over keychain-stored credentials. Generate one with [`claude setup-token`](</docs/en/authentication#generate-a-long-lived-token>). Claude Code uses the token you set for the whole session. To replace an expired token, generate a new one and restart `CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE`| Removed in v2.1.160 and now a no-op. Previously pinned [fast mode](</docs/en/fast-mode>) to Claude Opus 4.6 instead of the current default. Opus 4.6 no longer supports fast mode `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`| Maximum length of content-bearing OpenTelemetry attributes (model responses, tool content, system prompts, raw API bodies), truncation marker included, in UTF-16 code units (default: 61440, i.e. 60 KB). Raise it only if your telemetry backend accepts attribute values larger than 64 KB, or lower it to cut telemetry volume. Requires Claude Code v2.1.214 or later. See [Monitoring](</docs/en/monitoring-usage>) `CLAUDE_CODE_OTEL_DIAG_STDERR`| Set to `1` to write OpenTelemetry exporter diagnostic errors to stderr. By default these errors only appear with `--debug`, so a misconfigured exporter such as a Prometheus port collision otherwise fails silently. Requires Claude Code v2.1.179 or later. See [Monitoring](</docs/en/monitoring-usage>) @@ -322,7 +327,7 @@ `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`| Set to `1` to strip Anthropic and cloud provider credentials from subprocess environments (Bash tool, hooks, MCP stdio servers). The parent Claude process keeps these credentials for API calls, but child processes cannot read them, reducing exposure to prompt injection attacks that attempt to exfiltrate secrets via shell expansion. On Linux, this also runs Bash subprocesses in an isolated PID namespace so they cannot read host process environments via `/proc`; as a side effect, `ps`, `pgrep`, and `kill` cannot see or signal host processes. `claude-code-action` sets this automatically when `allowed_non_write_users` is configured `CLAUDE_CODE_SYNC_PLUGIN_INSTALL`| Set to `1` in non-interactive mode (the `-p` flag) to wait for plugin installation to complete before the first query. Without this, plugins install in the background and may not be available on the first turn. Combine with `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` to bound the wait `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS`| Timeout in milliseconds for synchronous plugin installation. When exceeded, Claude Code proceeds without plugins and logs an error. No default: without this variable, synchronous installation waits until complete -`CLAUDE_CODE_SYNC_SKILLS`| Set to `1` to download your enabled claude.ai skills into `~/.claude/skills/` before the first query and resync every 10 minutes. Applies only in non-interactive mode with the `-p` flag. Requires claude.ai authentication. [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions receive your enabled claude.ai skills automatically; you don’t need to set this there +`CLAUDE_CODE_SYNC_SKILLS`| Set to `1` to download your enabled claude.ai skills into `~/.claude/skills/synced/` before the first query and resync every 10 minutes. The `synced` folder name is [reserved for this download](</docs/en/skills#where-skills-live>). Before v2.1.227, the skills downloaded into `~/.claude/skills/` directly. Applies only in non-interactive mode with the `-p` flag. Requires claude.ai authentication. [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions receive your enabled claude.ai skills automatically; you don’t need to set this there `CLAUDE_CODE_SYNC_SKILLS_INSTALL_TIMEOUT_MS`| Timeout in milliseconds for a mid-session skills resync when `CLAUDE_CODE_SYNC_SKILLS` is set (default: 30000). Bounds the download triggered when the host requests a skill reload during the session. When exceeded, the resync stops and remaining downloads continue in the background `CLAUDE_CODE_SYNC_SKILLS_WAIT_TIMEOUT_MS`| Timeout in milliseconds for the first query to wait on the initial skills sync when `CLAUDE_CODE_SYNC_SKILLS` is set (default: 5000). When exceeded, the query proceeds and remaining skill downloads continue in the background `CLAUDE_CODE_SYNTAX_HIGHLIGHT`| Set to `false` to disable syntax highlighting in diff output. Useful when colors interfere with your terminal setup. To also disable highlighting in code blocks and file previews, use the [`syntaxHighlightingDisabled`](</docs/en/settings>) setting @@ -330,7 +335,7 @@ `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_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 a [held cross-session message](</docs/en/cross-session-messaging#control-inbound-messages>) awaiting approval, before Claude Code cancels the dialog or drops the default-held message; permission prompts and `AskUserQuestion` questions use their own flows and aren’t governed by it. Overrides the [`dialogExpiry`](</docs/en/settings#available-settings>) setting; `0` or a negative value disables the deadline +`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. [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#available-settings>) 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>) `CLAUDE_CODE_USE_FOUNDRY`| Use [Microsoft Foundry](</docs/en/microsoft-foundry>) @@ -348,7 +353,7 @@ `CLAUDE_PID`| Claude Code sets this to its own process ID in the subprocesses it spawns: Bash and PowerShell tool commands and hook commands. On Linux, the Bash tool’s shell integration uses it to refuse a `pkill` pattern that would match the Claude Code process itself; see [the error reference](</docs/en/errors#pkill-pattern-matches-the-claude-code-process>). Read it from your own scripts to identify or signal the parent Claude Code process deliberately. Requires Claude Code v2.1.214 or later `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX`| Prefix for auto-generated [Remote Control](</docs/en/remote-control>) session names when no explicit name is provided. Defaults to your machine’s hostname, producing names like `myhost-graceful-unicorn`. The `--remote-control-session-name-prefix` CLI flag sets the same value for a single invocation `CLAUDE_STREAM_IDLE_TIMEOUT_MS`| Timeout in milliseconds before the event- and byte-level streaming idle watchdogs close a stalled connection. When you set this variable explicitly, the minimum is `300000` (5 minutes); lower values are silently clamped to absorb extended thinking pauses and proxy buffering, and the byte-level watchdog caps the value at 30 minutes. `CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS` takes precedence over this variable for the byte-level watchdog. For the per-watchdog unset defaults, see [Streaming idle watchdogs](</docs/en/network-config#streaming-idle-watchdogs>) -`CLAUDE_SUBAGENT_BG_SHELL_MAX_MS`| Maximum lifetime in milliseconds for a [background shell command](</docs/en/interactive-mode#background-bash-commands>) that a [subagent](</docs/en/sub-agents>) started. Default `3600000` (60 minutes). When you set `0`, Claude Code applies the default instead of removing the cap. Claude Code doesn’t cap main-session background commands this way; see [How backgrounding works](</docs/en/interactive-mode#how-backgrounding-works>) for the memory-pressure limit that covers them +`CLAUDE_SUBAGENT_BG_SHELL_MAX_MS`| Maximum lifetime in milliseconds for a [background shell command](</docs/en/interactive-mode#background-bash-commands>) that a [subagent](</docs/en/sub-agents>) started. Default `3600000` (60 minutes). When you set `0`, Claude Code applies the default instead of removing the cap. When the subagent runs in the foreground, Claude Code also ends the command when that subagent gives its final response, regardless of this cap. See [the background command lifetime rules](</docs/en/tools-reference#background-commands>). Claude Code doesn’t cap main-session background commands this way. For the memory-pressure limit that covers them, see [How backgrounding works](</docs/en/interactive-mode#how-backgrounding-works>) `DEBUG`| Set to `1` to enable debug mode, equivalent to launching with [`--debug`](</docs/en/cli-reference#cli-flags>). Debug logs are written to `~/.claude/debug/<session-id>.txt`, or to the path set by `CLAUDE_CODE_DEBUG_LOGS_DIR`. Only the truthy values `1`, `true`, `yes`, and `on` enable debug mode, so namespace patterns like `DEBUG=express:*` set for other tools do not trigger it `DISABLE_AUTOUPDATER`| Set to `1` to disable automatic background updates. Manual `claude update` still works. Use `DISABLE_UPDATES` to block both `DISABLE_AUTO_COMPACT`| Set to `1` to disable automatic compaction when approaching the context limit. The manual `/compact` command remains available. Use when you want explicit control over when compaction occurs. Overrides the [`autoCompactEnabled`](</docs/en/settings#available-settings>) setting @@ -376,16 +381,16 @@ `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#available-settings>) 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 1-hour TTL automatically. 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 `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: all MCP tools deferred by default, but loaded upfront on Google Cloud’s Agent Platform models earlier than the Claude 4.5 generation, when `ANTHROPIC_BASE_URL` points to a non-first-party host, or on a Microsoft Foundry deployment hosted on Azure. Values: `true` (always defer and send the beta header, except on a Microsoft Foundry deployment hosted on Azure and on Google Cloud’s Agent Platform models earlier than the Claude 4.5 generation, where Claude Code still loads tools upfront; requests fail on proxies that don’t support `tool_reference`), `auto` (threshold mode: load upfront if tools fit within 10% of context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `false` (load all upfront). Ignored when `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` is set, which forces all tools to load upfront. 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` +`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` `FALLBACK_FOR_ALL_PRIMARY_MODELS`| Set to any non-empty value, such as `1`, to make every model stop retrying with a repeated-overload error when no fallback model is configured. **Setting it to`0` or `false` still enables this**, unlike most on/off variables; unset the variable to restore the default retry behavior. Without it, models Claude Code recognizes as Opus, Fable 5, or Mythos models stop retrying this way when you authenticate with an API key or a [third-party provider](</docs/en/third-party-integrations>) rather than a Claude subscription. As of v2.1.160, a configured [fallback model chain](</docs/en/model-config#fallback-model-chains>) triggers on repeated overload errors for any primary model, so this variable does not affect switching to a fallback model `FORCE_AUTOUPDATE_PLUGINS`| Set to `1` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` -`FORCE_HYPERLINK`| Set to `1` to enable clickable OSC 8 hyperlinks when your terminal supports them but isn’t auto-detected, or `0` to disable them. Claude Code parses this value as a number, not a boolean, so word spellings such as `false`, `no`, or `off` enable hyperlinks rather than disabling them +`FORCE_HYPERLINK`| Set to `1` to enable clickable OSC 8 hyperlinks when your terminal supports them but isn’t auto-detected, or `0` to disable them. When unset, Claude Code enables hyperlinks only when it detects terminal support. Claude Code parses this value as a number, not a Boolean, so a value such as `false`, `no`, or `off` enables hyperlinks rather than disabling them. Claude Code renders the footer PR badge as a hyperlink even when it can’t detect terminal support, such as over SSH. Set `0` to render the badge as plain text `FORCE_PROMPT_CACHING_5M`| Set to `1` to force the 5-minute prompt cache TTL even when 1-hour TTL would otherwise apply. Overrides `ENABLE_PROMPT_CACHING_1H` `HTTP_PROXY`| Specify HTTP proxy server for network connections `HTTPS_PROXY`| Specify HTTPS proxy server for network connections `IS_DEMO`| Set to any non-empty value, such as `1`, to enable demo mode: hides your email and organization name from the header and `/status` output, and skips onboarding. **Setting it to`0` or `false` still enables demo mode**, unlike most on/off variables; unset the variable to turn it off. Useful when streaming or recording a session `MAX_MCP_OUTPUT_TOKENS`| Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens. Tools that declare [`anthropic/maxResultSizeChars`](</docs/en/mcp#raise-the-limit-for-a-specific-tool>) use that character limit for text content instead, but image content from those tools is still subject to this variable (default: 25000) -`MAX_STRUCTURED_OUTPUT_RETRIES`| Number of times to retry when the model’s response fails validation against the [`--json-schema`](</docs/en/cli-reference#cli-flags>) in non-interactive mode (the `-p` flag). Defaults to 5 +`MAX_STRUCTURED_OUTPUT_RETRIES`| Number of times Claude Code retries when the model’s response fails validation against the [`--json-schema`](</docs/en/cli-reference#cli-flags>) in non-interactive mode with the `-p` flag. The same retry count applies when a [workflow](</docs/en/workflows>) subagent’s structured output fails validation. Defaults to 5 `MAX_THINKING_TOKENS`| Fixed token budget for [extended thinking](<https://platform.claude.com/docs/en/build-with-claude/extended-thinking>). Claude Code caps it at one token below the request’s max output tokens and never below 1,024; see `CLAUDE_CODE_MAX_OUTPUT_TOKENS` for how that limit is set. When unset and thinking is enabled, models with [adaptive reasoning](</docs/en/model-config#adjust-effort-level>) choose their own thinking depth, and other models use the cap. Set to `0` to disable thinking on the Anthropic API, except on Fable 5, which cannot have thinking turned off; on [third-party providers](</docs/en/third-party-integrations>), `0` omits the `thinking` parameter instead. Nonzero values are ignored on adaptive reasoning models unless `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` is set `MCP_CLIENT_SECRET`| OAuth client secret for MCP servers that require [pre-configured credentials](</docs/en/mcp#use-pre-configured-oauth-credentials>). Avoids the interactive prompt when adding a server with `--client-secret` `MCP_CONNECTION_NONBLOCKING`| Controls whether startup waits for MCP servers to connect before the first query. MCP startup is non-blocking by default: servers connect in the background and their tools become available as they finish; before v2.1.142, the blocking wait was the default. Set to `0` to restore the blocking 5-second connection wait. Servers configured with [`alwaysLoad: true`](</docs/en/mcp#exempt-a-server-from-deferral>) still make startup wait regardless, except when served from the [discovery cache](</docs/en/mcp#managing-your-servers>), since their tools must be present when the first prompt is built. In non-interactive mode (`-p`), Claude Code also waits for still-pending servers before the first turn regardless of this variable, with a longer deadline when you pass [`--mcp-config`](</docs/en/cli-reference#cli-flags>) explicitly; see that flag’s entry for the cached-server exception @@ -393,6 +398,7 @@ `MCP_DISCOVERY_CACHE`| Set to `0` to turn off the cross-process MCP discovery cache, so every server connects at startup instead of showing the [`connects on first use` cached status](</docs/en/mcp#managing-your-servers>) and connecting on its first tool call. The cached status requires Claude Code v2.1.221 or later `MCP_OAUTH_CALLBACK_PORT`| Fixed port for the OAuth redirect callback, as an alternative to `--callback-port` when adding an MCP server with [pre-configured credentials](</docs/en/mcp#use-pre-configured-oauth-credentials>) `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE`| Maximum number of remote MCP servers (HTTP/SSE) to connect in parallel during startup (default: 20) +`MCP_SDK_GENERATION`| Pin which MCP client runtime this process uses, the implementation behind [MCP server connections](</docs/en/mcp>), while Claude Code migrates from its v1 runtime to v2. Set `v1` to stay on the current runtime or `v2` to opt in early. Without the variable, a gradual rollout decides, and defaults to v1. On Claude Code v2.1.221 or later, the v2 runtime checks the issuer an MCP OAuth server returns in its authorization response and fails the sign-in with an error that begins `Issuer mismatch in authorization response` when it doesn’t match. The v1 runtime doesn’t run this check. If you set an unrecognized value, Claude Code ignores it and writes a warning to the debug log. Claude Code reads the value once per process. Requires Claude Code v2.1.218 or later `MCP_SERVER_CONNECTION_BATCH_SIZE`| Maximum number of local MCP servers (stdio) to connect in parallel during startup (default: 3) `MCP_TIMEOUT`| Timeout in milliseconds for MCP server startup (default: 30000, or 30 seconds) `MCP_TOOL_TIMEOUT`| Timeout in milliseconds for MCP tool execution (default: 100000000, about 28 hours). For an HTTP, SSE, or claude.ai connector server, each request also times out after 60 seconds by default; set this variable, or the per-server `timeout`, above 60000 to raise that per-request limit. A lower value still shortens the overall tool-execution timeout but leaves the per-request limit at 60 seconds. Stdio and WebSocket servers have no per-request timer. A per-server `timeout` field in `.mcp.json` overrides this for that server. A per-server `timeout` of at least 1000 also sets the minimum idle window for that server’s tool calls, so `CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT` never aborts them sooner; this floor requires Claude Code v2.1.203 or later. For the env variable, values below 1000 are floored to one second; for the per-server field, values below 1000 are ignored
modified Error reference View current →
Show diff (747 lines)
--- a/errors.md +++ b/errors.md @@ -16,11 +16,15 @@ `API Error: Repeated 529 Overloaded errors`| Server errors `Request timed out`| Server errors, or Network if the message mentions your internet connection `Server error mid-response. The response above may be incomplete.`| Server errors +`Connection lost mid-response` / `Your computer went to sleep mid-response` / `The response stopped arriving`| Server errors `Connection closed mid-response` / `Response stalled mid-stream`| Server errors +`Connection lost before a response was produced` / `Your computer went to sleep before a response was produced` / `The response stalled before a response was produced`| Automatic retries `Connection closed while thinking` / `Response stalled while thinking`| Automatic retries +`Connection lost while your computer was asleep`| Automatic retries `<model> is temporarily unavailable, so auto mode cannot determine the safety of...`| Server errors `Auto mode could not evaluate this action and is blocking it for safety`| Server errors `Auto mode classifier transcript exceeded context window`| Server errors +`Agent aborted: auto mode classifier request refused by the safety safeguard`| Server errors `Agent terminated early due to an API error`| Server errors `You've hit your session limit` / `You've hit your weekly limit`| Usage limits `Usage credits required for 1M context`| Usage limits @@ -28,25 +32,37 @@ `Request rejected (429)`| Usage limits `Credit balance is too low`| Usage limits `Could not update your spend limit`| Usage limits +`spend limit reached` / `spend limit unavailable`| Usage limits `Not logged in · Please run /login`| Authentication `Could not resolve authentication method`| Authentication `Invalid API key`| Authentication `Your apiKeyHelper script is failing`| Authentication +`Invalid auth token · Fix external auth token`| Authentication +`Invalid ANTHROPIC_CUSTOM_HEADERS · Fix the environment variable`| Authentication +`Invalid request header from the environment · Fix the environment variable`| Authentication `This organization has been disabled`| Authentication `Your organization has disabled API key authentication`| Authentication `Your organization has disabled Claude subscription access`| Authentication `Routines are disabled by your organization's policy`| Authentication `Remote Control is only available when using Claude via api.anthropic.com`| Authentication +`OAuth token refresh failed — run /login to re-authenticate`| Authentication +`JWT refresh failed: no OAuth token — run /login`| Authentication +`Claude.ai login expired`| Authentication +`Claude.ai login was rejected — run /login, then /remote-control`| Authentication +`OAuth token unavailable — run /login to restore Remote Control`| Authentication `OAuth token revoked` / `OAuth token has expired`| Authentication `API Error: 401 Invalid authentication credentials`| Authentication `Login expired · Please run /login`| Authentication `Failed to authenticate: OAuth session expired and could not be refreshed`| Authentication +`Anthropic profile login expired · Re-authenticate your Anthropic profile`| Authentication `does not meet scope requirement user:profile`| Authentication `claude.ai rejected the session token` / `session token rejected`| Authentication `AWS credentials expired or invalid`| Authentication `AWS authentication failed`| Authentication `AWS default-chain credential resolve timed out`| Authentication +`Could not load the default credentials` on Google Cloud’s Agent Platform| Automatic retries `Unable to connect to API`| Network +`Connection refused —` / `Can't reach the API server —` / `No internet route —` / `Couldn't connect through your proxy` / `Connection dropped`, each ending with an error code in parentheses| Network `Unable to connect to Anthropic services` during setup| Network `Socket is closed`| Network `Waiting for API response · will retry in`| Automatic retries, or Network if it persists @@ -56,7 +72,8 @@ `403` with `x-deny-reason: host_not_allowed` in a cloud or routine session| Network `403` with `This GraphQL query is not enabled for this session` in a cloud session| [GitHub proxy](</docs/en/cloud-environments#github-proxy>) `Couldn't reconnect to your Remote Control session`| Network -`Prompt is too long`| Request errors +`Couldn't share the transcript.`| Network +`Prompt is too long` / `Input is too long for requested model`| Request errors `Context exceeds the ...-token limit by ... tokens` in `/context` output| Request errors `Error during compaction: Conversation too long`| Request errors `Request too large`| Request errors @@ -82,14 +99,19 @@ `Error: --json-schema is not a valid JSON Schema`| Command-line errors `Error: Settings file exceeds the 2MiB limit`| Command-line errors `Error: Workspace not trusted` when starting Remote Control| Command-line errors +``claude import` is not yet available in this build`| Command-line errors +`Could not read Claude Code config`| Command-line errors `Could not import <server>: <reason>`| Command-line errors `Error: MCP tool <name> (passed via --permission-prompt-tool) not found`| Command-line errors -`Shell command failed for pattern "!`git ... origin/HEAD...`"`| Command-line errors +`Shell command failed for pattern "..."`, from `/security-review` or any skill that injects dynamic context| Command-line errors +`Shell command permission check failed for pattern "..."`, from a skill that injects dynamic context| Command-line errors +`Skill <name> requires bash (`shell: bash` in frontmatter) but Git Bash was not found`| Command-line errors `Input must be provided either through stdin or as a prompt argument when using --print`| Command-line errors `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 `Failed to resume the conversation`| Command-line errors +`No conversation found with session ID: <session-id>`| Command-line errors `Marketplace "<name>" is registered from an untrusted source`| Plugin errors `references ${user_config.*} in a shell-form command`| Plugin errors `Monitor "<name>" from plugin <plugin> references ${user_config.*} in its command`| Plugin errors @@ -99,8 +121,12 @@ `File is covered by a Read deny rule in your permission settings`| Tool errors `Error: this write left the memory index at MEMORY.md at ..., over its ... read limit`| Tool errors `pkill: refusing to run`| Tool errors +`Failed to write to <name>'s inbox — nothing was sent`| Tool errors +`Failed to write the plan approval request to the lead's inbox — plan not submitted`| 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 `This session was running agent '<name>', which is no longer available`| Background session errors `CLAUDE_CODE_PROCESS_WRAPPER: launcher ...`| Background session errors @@ -108,8 +134,12 @@ `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 +`Transcript writes are failing (...)`| Session saving warnings +`Transcript saving is off — CLAUDE_CODE_SKIP_PROMPT_HISTORY is set`| Session saving warnings +`Transcript saving is off — inherited CLAUDE_CODE_CHILD_SESSION marker`| Session saving warnings `Ignoring N permissions.allow entries from ... this workspace has not been trusted`| Configuration warnings `... is not matched by file permission checks`| Configuration warnings +`CLAUDE_CODE_DISABLE_1M_CONTEXT is set, but the 200K limit isn't enforced`| Configuration warnings Responses seem lower quality than usual| Response quality ## @@ -121,11 +151,17 @@ Claude Code retries transient failures up to 10 times with exponential backoff before showing you an error. It doesn’t always retry a failure that arrives partway through Claude’s response. When you see one of the errors on this page, Claude Code has already made whatever retries apply to that failure; the lists below say which failures get the full budget, which get a smaller one, and which get none. Claude Code retries these failures: * Server errors, overloaded responses, and request timeouts that arrive before any of Claude’s response has streamed. - * Dropped connections. When a connection drops partway through a request before Claude has completed any part of its response, including its thinking, Claude Code re-issues the request with the same backoff and the turn continues, even if some text had already started streaming. When it drops after Claude has finished thinking but before it has started any text or tool call, Claude Code instead re-issues the request up to two times in quick succession, and ends the turn with `Connection closed while thinking, before producing a response` if the connection keeps dropping at that point. - * A stalled response stream, when none of the response has arrived yet or when Claude has finished thinking but hasn’t started any text or tool call: Claude Code aborts the stalled connection and re-issues the request at most once, outside the 10-attempt budget above. If the response stalls a second time after Claude has finished thinking but before any text or tool call, Claude Code ends the turn with `Response stalled while thinking, before producing a response`. - * Temporary 429 throttles. When you’re signed in with a claude.ai subscription, this includes 429 throttles that don’t carry your plan’s quota headers. Before v2.1.199, Claude Code retried those throttles only for API key and Enterprise sign-ins. - -Claude Code doesn’t retry these failures: + * Dropped connections. When a connection drops partway through a request before Claude has completed any part of its response, including its thinking, Claude Code re-issues the request with the same backoff and the turn continues, even if some text had already started streaming. When it drops after Claude has finished thinking but before it has started any text or tool call, Claude Code instead re-issues the request up to two times in quick succession, and ends the turn with `Connection lost before a response was produced` if the connection keeps dropping at that point. + * A connection that Claude Code detects was broken by your computer going to sleep partway through a request. Claude Code counts it as a dropped connection under the rules above; once the retry label names the specific reason, it reads `Connection lost while your computer was asleep`, and if the turn ends after Claude has finished thinking but before any text or tool call, the message reads `Your computer went to sleep before a response was produced`. + * A stalled response stream, when none of the response has arrived yet or when Claude has finished thinking but hasn’t started any text or tool call: Claude Code aborts the stalled connection and re-issues the request at most once, outside the 10-attempt budget above. If the response stalls a second time after Claude has finished thinking but before any text or tool call, Claude Code ends the turn with `The response stalled before a response was produced`. + * Temporary 429 throttles, but not a gateway’s spend-limit `429`, which isn’t a throttle; see Spend limit reached. + * When you’re signed in with a claude.ai subscription, this includes 429 throttles that don’t carry your plan’s quota headers. Before v2.1.199, Claude Code retried those throttles only for API key and Enterprise sign-ins. + * A request rejected because the input plus `max_tokens` exceeds the context limit. Re-sending it unchanged would fail the same way, so Claude Code retries with a reduced `max_tokens`, and stops retrying and compacts instead in two cases: + * When no reduction can fit, for example when the conversation itself nearly fills the context window. + * When a retry can’t shrink `max_tokens` any further. Before v2.1.218, Claude Code could re-send a reduced request that still didn’t fit, such as when the extended thinking budget exceeded the remaining context, until the retry budget ran out. + * An expired or missing Google Cloud credential on [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), which surfaces as an error such as `Could not load the default credentials`. Claude Code discards its cached credentials and retries up to two times, running your [`gcpAuthRefresh`](</docs/en/google-vertex-ai#advanced-credential-configuration>) command if you configured one, then reports the error so you can re-authenticate right away. [Google Cloud’s Agent Platform troubleshooting](</docs/en/google-vertex-ai#troubleshooting>) covers re-authenticating. Before v2.1.228, Claude Code retried a failing credential through the full retry budget before showing the error. + +Before v2.1.227, `Connection lost before a response was produced` read `Connection closed while thinking, before producing a response` and `The response stalled before a response was produced` read `Response stalled while thinking, before producing a response`. Claude Code doesn’t retry these failures: * A TLS certificate validation failure, such as a TLS-inspecting proxy, a missing `NODE_EXTRA_CA_CERTS` bundle, or an expired certificate. Claude Code reports the error on the first attempt, so you can fix the certificate setup right away; see SSL certificate errors. Claude Code still retries transient TLS conditions such as a handshake timeout. Before v2.1.199, Claude Code retried certificate failures through the full retry budget before showing the error. * A server error, dropped connection, or stalled stream that arrives after Claude has completed a block of text or a tool call, or has started one after finishing its thinking, but before it finishes the response. Claude Code could execute the same tool calls twice if it re-ran the request, so it keeps what Claude completed and shows an incomplete-response notice. Claude Code still runs any tool calls Claude completed and continues the turn from their results. Before v2.1.199, Claude Code discarded the partial output and reported the whole turn as an error when a server error arrived mid-stream. @@ -220,17 +256,19 @@ A streaming request failed while the response was still in progress, after Claude had completed a block of text or a tool call, or had started one after finishing its thinking. Re-sending the request could run the same tool calls twice, so Claude Code keeps the output Claude completed and appends this notice instead of discarding the turn. Which variant you see names the cause: API Error: Server error mid-response. The response above may be incomplete. - API Error: Connection closed mid-response. The response above may be incomplete. - API Error: Response stalled mid-stream. The response above may be incomplete. + API Error: Connection lost mid-response. The response above may be incomplete. + API Error: Your computer went to sleep mid-response. The response above may be incomplete. + API Error: The response stopped arriving. The response above may be incomplete. * `Server error mid-response`: a mid-stream overloaded or 5xx server error. This variant requires Claude Code v2.1.199 or later; before then that case discarded the partial output and reported the whole turn as an error. - * `Connection closed mid-response`: the connection dropped. - * `Response stalled mid-stream`: the stream stopped sending data. Before v2.1.222, this variant could also appear on [gateway](</docs/en/gateways>) connections reached through `ANTHROPIC_BASE_URL` or `ANTHROPIC_AWS_BASE_URL` while the server’s keep-alive pings were still arriving, because Claude Code counted only parsed response events there; upgrading stops those spurious timeouts on those routes. Gateways reached through a provider base URL such as `ANTHROPIC_BEDROCK_BASE_URL` aren’t wrapped by the byte watchdog; see [Streaming idle watchdogs](</docs/en/network-config#streaming-idle-watchdogs>). - -When one of these failures lands at another point in the turn, Claude Code handles it without this notice: + * `Connection lost mid-response`: the connection dropped. + * `Your computer went to sleep mid-response`: Claude Code detected that your computer went to sleep while the response was streaming. Once your computer wakes, Claude Code treats the connection as broken and stops reading from it. + * `The response stopped arriving`: the connection stayed open but stopped delivering data, so the streaming idle watchdog aborted it. Before v2.1.222, Claude Code could also report this failure on [gateway](</docs/en/gateways>) connections reached through `ANTHROPIC_BASE_URL` or `ANTHROPIC_AWS_BASE_URL` while the server’s keep-alive pings were still arriving, because it counted only parsed response events there; upgrading stops those spurious timeouts on those routes. Gateways reached through a provider base URL such as `ANTHROPIC_BEDROCK_BASE_URL` aren’t wrapped by the byte watchdog; see [Streaming idle watchdogs](</docs/en/network-config#streaming-idle-watchdogs>). + +Before v2.1.227, `Connection lost mid-response` read `Connection closed mid-response` and `The response stopped arriving` read `Response stalled mid-stream`. When one of these failures lands at another point in the turn, Claude Code handles it without this notice: * Earlier in the response, Claude Code either retries the failure or ends the turn with a different error. See Automatic retries. - * When one of these failures arrives after Claude has finished the response, Claude Code keeps the complete response and ends the turn normally, without this notice. Before v2.1.222, Claude Code showed the `Connection closed mid-response` or `Response stalled mid-stream` notice when the connection dropped or stalled after the response finished, and reported the turn as an error even though the response was complete. + * When one of these failures arrives after Claude has finished the response, Claude Code keeps the complete response and ends the turn normally, without this notice. Before v2.1.222, Claude Code showed this notice when the connection dropped or stalled after the response finished, and reported the turn as an error even though the response was complete. **What to do:** @@ -269,7 +307,7 @@ Auto mode could not evaluate this action and is blocking it for safety — a safety check separate from auto mode blocked this request because of earlier conversation content — it isn't about the action itself — run with --debug for details -**What to do:** +Claude Code denies the action but tells Claude this isn’t a judgment that the action is unsafe, and to continue with other tasks rather than retry. These denials don’t count toward [auto mode’s pause thresholds](</docs/en/permission-modes#when-auto-mode-falls-back>). In [non-interactive mode](</docs/en/headless>) the run aborts with `Agent aborted: auto mode classifier request refused by the safety safeguard in headless mode`, since there is no user to prompt and the refusal repeats on every retry. Before v2.1.225, Claude Code counted these refusals toward the pause thresholds and returned the same rejection message as a genuine classifier block. **What to do:** * This is not a decision about your action. Content already in your conversation triggered a safety filter on the API when auto mode sent the conversation to the classifier * Retrying will not help; the same conversation content will trigger the filter again @@ -384,6 +422,23 @@ ​ +Spend limit reached + +You connect through a [Claude apps gateway](</docs/en/claude-apps-gateway>) and have passed a [spend cap](</docs/en/claude-apps-gateway-spend-limits>) your gateway operator set. The gateway blocks your requests until the named period resets or the operator raises the cap. It marks each blocked `429` response `x-should-retry: false`, so Claude Code shows this message without retrying. + + spend limit reached (daily; resets 2026-08-09 00:00 UTC) + +The message names the cap’s period and reset time, and when the operator configured a `blocked_message`, their instructions follow it. Before v2.1.225, the message read only `spend limit reached`; a gateway on an older version still sends that shorter form. **What to do:** + + * Wait for the reset time the message names, or follow the operator’s instructions if the message carries them + * Ask your gateway operator to raise the cap if you hit it routinely + +A related message, `spend limit unavailable`, means the gateway could not read its spend records and blocked the request as a precaution rather than over your cap. It usually clears on its own; if it persists, tell your gateway operator. + +### + +​ + Credit balance is too low Your Console organization has run out of prepaid credits. @@ -462,11 +517,11 @@ Invalid API key -The `ANTHROPIC_API_KEY` environment variable or `apiKeyHelper` script returned a key the API rejected. +The `ANTHROPIC_API_KEY` environment variable or `apiKeyHelper` script returned a key the API rejected, or Claude Code blocked a key from `ANTHROPIC_API_KEY` before sending it. Invalid API key · Fix external API key -**What to do:** +When the message continues past `Fix external API key` with a description such as `Invalid X-Api-Key header value from ANTHROPIC_API_KEY: it contains a line break at character 41 (120 characters on 2 lines).`, the API never saw the key. Claude Code found a character that HTTP headers can’t carry and stopped the request before sending it. See Invalid request header value for how to read the description and fix the value. **What to do:** * Check for typos and confirm the key has not been revoked in the [Console](<https://platform.claude.com/settings/keys>) * In the same shell, run `env | grep ANTHROPIC`, or in PowerShell `Get-ChildItem Env:ANTHROPIC*`. Tools like direnv, dotenv shell plugins, and IDE terminals can load a stale key from a `.env` file in your project without you setting it explicitly. @@ -480,7 +535,11 @@ Your apiKeyHelper script is failing -The command configured in the [`apiKeyHelper`](</docs/en/settings#available-settings>) setting exited with an error, timed out, or printed nothing to stdout. Without a key from the script, the request reaches the API with a placeholder credential, and the API rejects it with `401`. +Claude Code ran the command in your [`apiKeyHelper`](</docs/en/settings#available-settings>) setting and didn’t get a key back. Without one, the request reaches the API with a placeholder credential, and the API rejects it with `401`. The `Authentication` panel in the terminal shows which of these happened: + + * The command exited with an error or timed out + * The command printed nothing to stdout + * The command printed something besides the key, such as a login banner or a log line. The panel shows `returned output that cannot be used as an API key` and says what’s wrong, without repeating the output. Before v2.1.227, Claude Code sent whatever the command printed, after trimming surrounding whitespace. Your apiKeyHelper script is failing · This usually means you need to re-authenticate with your provider · Run /status to see the script's error output @@ -488,8 +547,36 @@ * Run the command configured in `apiKeyHelper` directly in your shell to reproduce the failure * If the command reports an expired session, re-authenticate with your credential provider, for example by signing in to your SSO or secrets vault again - * Fix the command so it prints the key to stdout and exits with code 0. See [rotate credentials with apiKeyHelper](</docs/en/llm-gateway-connect#rotate-credentials-with-apikeyhelper>) for a working setup. + * Fix the command so it prints only the key to stdout, as a single token of printable ASCII up to 16,384 characters, and exits with code 0. See [rotate credentials with apiKeyHelper](</docs/en/llm-gateway-connect#rotate-credentials-with-apikeyhelper>) for a working setup. * Run `/status` to confirm `apiKeyHelper` is the active credential source. Each time the command fails, its exit code and error output appear in an `Authentication` panel in the terminal. Before v2.1.212, the panel was titled `Cloud authentication`. + +### + +​ + +Invalid request header value + +A value Claude Code was about to send as a request header contains a character that HTTP headers can’t carry: a line break, a NUL byte, or a character above `U+00FF`, such as a curly quote or a zero-width space. Claude Code stops the request before anything is sent and names the variable or setting to fix. The usual cause is a credential pasted from a document or chat that carried an invisible character or a stray line break. Claude Code runs this check when it sends requests to the Claude API directly or through an [LLM gateway](</docs/en/llm-gateway>). On a third-party cloud provider such as [Amazon Bedrock](</docs/en/amazon-bedrock>), Claude Code doesn’t run it before sending. + + Invalid auth token · Fix external auth token + Invalid ANTHROPIC_CUSTOM_HEADERS · Fix the environment variable + Invalid request header from the environment · Fix the environment variable + +The first part of the message depends on where the bad value came from: + + * `Invalid auth token`: a bearer token from [`ANTHROPIC_AUTH_TOKEN`](</docs/en/env-vars>) or [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/env-vars>) + * `Invalid ANTHROPIC_CUSTOM_HEADERS`: a header name or value you set in [`ANTHROPIC_CUSTOM_HEADERS`](</docs/en/env-vars>). The description counts which `Name: Value` pair is at fault, such as `distinct header 2 of 3 parsed from ANTHROPIC_CUSTOM_HEADERS`, without repeating the name or value, since you chose both. + * `Invalid request header from the environment`: a value Claude Code copies into a request header from another environment variable, such as `CLAUDE_AGENT_SDK_CLIENT_APP`. The description names the variable to fix. + +Claude Code reports a bad `ANTHROPIC_API_KEY` caught by this check as Invalid API key, with the same trailing description. It reports a bad saved `/login` credential as Not logged in instead; run `/login` to save a fresh one. An [`apiKeyHelper`](</docs/en/settings#available-settings>) script’s output never reaches this check: Claude Code validates it when the script runs, and output an HTTP header can’t carry fails with Your apiKeyHelper script is failing. After the second `·`, the message describes the problem, as in this full example: + + Invalid auth token · Fix external auth token · Invalid Authorization header value from ANTHROPIC_AUTH_TOKEN: it contains a line break at character 41 (120 characters on 2 lines). + +Positions count characters starting at one. The description is built from fixed phrases and character counts, so it never includes the value itself. It names the offending character only when it is a well-known invisible or typographic character, such as a byte-order mark, a zero-width space, or a curly quote, and reports anything else as `a non-ASCII character`. **What to do:** + + * Re-set the variable or setting the message names, retyping the characters around the reported position rather than pasting from the same source again + * For `ANTHROPIC_CUSTOM_HEADERS`, keep one `Name: Value` pair per line and rewrite the pair the message counts + * Run `/status` to confirm which credential source is active ### @@ -553,7 +640,7 @@ Routines are disabled by your organization’s policy -An Owner in your Team or Enterprise organization has turned off routines at the organization level. The error appears when you try to create or run a routine, including from `/schedule` and the [Routines](</docs/en/routines>) UI on claude.ai/code. +An Owner in your Team or Enterprise organization has turned off routines at the organization level. The error appears when you try to create or run a routine, for example from the [Routines](</docs/en/routines>) UI on claude.ai/code. On Claude Code v2.1.227 or later, the same setting also [hides `/schedule`](</docs/en/routines#troubleshooting>) in the CLI. Routines are disabled by your organization's policy. @@ -570,20 +657,56 @@ The session isn’t talking to the Anthropic API directly, so there is no claude.ai backend for [Remote Control](</docs/en/remote-control>) to pair with. - Remote Control is only available when using Claude via api.anthropic.com. - -This appears on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry. As of v2.1.196 it also appears when [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) points at a host other than `api.anthropic.com`, such as an [LLM gateway](</docs/en/llm-gateway>) or proxy, even when you sign in with claude.ai. **What to do:** - - * Unset `ANTHROPIC_BASE_URL` and restart the session, or start Remote Control from a session that talks to the Anthropic API directly + Remote Control is only available when using Claude via api.anthropic.com. CLAUDE_CODE_USE_BEDROCK is set, so this session is using Amazon Bedrock — unset it (or run in a shell without it) to use Remote Control. + +A second sentence explains what routed the session away from the Anthropic API; before v2.1.219, the message was the first sentence alone. Depending on the cause, the message names: + + * A `CLAUDE_CODE_USE_*` provider variable, such as `CLAUDE_CODE_USE_BEDROCK` for [Amazon Bedrock](</docs/en/amazon-bedrock>) or `CLAUDE_CODE_USE_VERTEX` for [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>) + * [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) pointing at a host other than `api.anthropic.com`, such as an [LLM gateway](</docs/en/llm-gateway>) or proxy, even when you sign in with claude.ai; before v2.1.196, a custom base URL didn’t block Remote Control + * An enterprise [cloud gateway](</docs/en/claude-apps-gateway>) sign-in made through `/login`, which doesn’t support Remote Control and has no variable to unset + +**What to do:** + + * Unset the variable the message names, such as `CLAUDE_CODE_USE_BEDROCK` or `ANTHROPIC_BASE_URL`, and restart the session, or start Remote Control from a session that talks to the Anthropic API directly + * If the variable isn’t set in your shell, check the `env` key in your [settings files](</docs/en/settings#settings-files>), which applies environment variables to every session * For this and the other Remote Control startup messages, see [Troubleshoot Remote Control](</docs/en/remote-control#troubleshooting>) ### ​ +Remote Control couldn’t refresh your login + +Claude Code runs a live [Remote Control](</docs/en/remote-control>) connection on short-lived credentials that it obtains and renews using your saved claude.ai login. When Claude Code can’t produce a login token that claude.ai accepts, whether while connecting or mid-session, it stops Remote Control and shows the reason in a warning and a transcript line that starts with `Remote Control disconnected`. Your local session keeps running without Remote Control. + + Remote Control disconnected — Claude.ai login expired — run /login to restore Remote Control + Remote Control disconnected — Claude.ai login expired — run /login, then /remote-control + Remote Control disconnected — Claude.ai login was rejected — run /login, then /remote-control + Remote Control disconnected — OAuth token unavailable — run /login to restore Remote Control + Remote Control disconnected — OAuth token refresh failed — run /login to re-authenticate + Remote Control disconnected — JWT refresh failed: no OAuth token — run /login + +The middle of the message names what failed: + + * `Claude.ai login expired` and `Claude.ai login was rejected`: claude.ai no longer accepts your saved login token, because it expired or was revoked + * `OAuth token unavailable`: Claude Code had no saved login token when the connection’s credential came due for renewal + * `OAuth token refresh failed`: Claude Code tried to refresh the saved login and the refresh failed, typically because the OAuth service rejected the stored refresh token + * `JWT refresh failed: no OAuth token`: Claude Code found no saved login token to renew with + +**What to do:** + + * Run `/login` to sign in again + * Run `/remote-control` to reconnect the session. Messages ending `run /login to restore Remote Control` don’t need this step: Claude Code reconnects on its own once you sign in. + +Before v2.1.224, `OAuth token refresh failed — run /login to re-authenticate` read `OAuth token refresh failed — re-authenticate, then re-enable Remote Control`, and `JWT refresh failed: no OAuth token — run /login` read `no OAuth token available for recovery (code <N>)`. The `Claude.ai login expired`, `Claude.ai login was rejected`, and `OAuth token unavailable` messages were added in v2.1.225. + +### + +​ + OAuth token revoked or expired -Your saved login is no longer valid. A revoked token means you signed out everywhere or an admin removed access; an expired token means the automatic refresh failed mid-session. Both messages report a rejection the API returned for a request Claude Code sent. When the saved login has already been cleared after a failed refresh, you see Login expired instead. +Your saved login is no longer valid. A revoked token means you signed out everywhere or an admin removed access; an expired token means the automatic refresh failed mid-session. Both messages report a rejection the API returned for a request Claude Code sent. When the saved login has already been cleared after a failed refresh, you see Login expired instead. If you authenticate with a long-lived token in [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/env-vars>), you see the same messages when that token expires or is revoked. OAuth token revoked · Please run /login OAuth token has expired · Please run /login @@ -593,6 +716,7 @@ * Run `/login` to sign in again * If the error returns within the same session after re-authenticating, run `/logout` first to fully clear the stored token, then `/login` + * If you authenticate with the `CLAUDE_CODE_OAUTH_TOKEN` environment variable, Claude Code keeps sending the value you set after a request fails with a 401, rather than switching to a stored login’s token. [`/status`](</docs/en/commands>) shows this credential as an `Auth token` row reading `CLAUDE_CODE_OAUTH_TOKEN`. Generate a fresh token with [`claude setup-token`](</docs/en/authentication#generate-a-long-lived-token>) and restart with it, or unset the variable and run `/login`. Before v2.1.225, Claude Code could replace the variable’s value mid-session with the short-lived access token from a stored login, and the session failed with 401 errors again once that token expired. * For repeated prompts to log in across launches, see the system clock and macOS Keychain checks in [Troubleshooting](</docs/en/troubleshoot-install#not-logged-in-or-token-expired>) * For other failures including `403 Forbidden` and OAuth browser issues, see [Login and authentication](</docs/en/troubleshoot-install#login-and-authentication>) @@ -637,6 +761,28 @@ ​ +Anthropic profile login expired + +Claude Code is authenticating through an Anthropic credential profile whose saved login credential has expired, and the profile holds no refresh credential Claude Code can use to renew it. Claude Code stops each request locally without retrying, because only re-authenticating the profile produces a working credential. + + Anthropic profile login expired · Re-authenticate your Anthropic profile + +This appears only when the active credential comes from an Anthropic credential profile, one you select with the `ANTHROPIC_PROFILE` environment variable or that Claude Code discovers as the active profile in your Anthropic configuration directory. Sessions that authenticate with `/login`, an API key, a bearer token such as `ANTHROPIC_AUTH_TOKEN`, or a third-party provider never see this message. Running `/login` doesn’t renew the profile credential. Whether a working login can take over instead depends on how the profile was selected: + + * When you set `ANTHROPIC_PROFILE` explicitly, the profile keeps precedence over a saved login, so signing in doesn’t stop the error. + * When Claude Code discovered the profile from your configuration directory, a working `/login` takes precedence over it, and Claude Code authenticates with your claude.ai or Console account instead. + +**What to do:** + + * Sign in to the profile again with the tool that created it, then retry + * If an administrator provisioned the profile’s credential, ask them to issue a new one + * Run `/status` to confirm the active credential source and profile name + * To stop using the profile, unset `ANTHROPIC_PROFILE` if you set it, then authenticate another way, such as `/login` or `ANTHROPIC_API_KEY` + +### + +​ + OAuth scope requirement The stored token predates a permission scope that a newer feature needs. You see this most often from `/usage` and the status line usage indicator: @@ -718,7 +864,7 @@ Network and connection errors -These errors mean a network request from Claude Code failed to reach its destination, or something between Claude Code and the API altered the response on its way back. They usually originate in your local network, proxy, or firewall, or in the cloud environment’s network policy. +Most of these errors mean a network request from Claude Code failed to reach its destination, or something between Claude Code and the API altered the response on its way back; where an entry also has a local cause, such as a failed archive write, its body says so. They usually originate in your local network, proxy, or firewall, or in the cloud environment’s network policy. ### @@ -726,16 +872,18 @@ Unable to connect to API -The TCP connection to the API failed or never completed. +The TCP connection to the API failed or never completed. For the common connection error codes, the message names the kind of failure and keeps the code in parentheses: Unable to connect to API. Check your internet connection - Unable to connect to API (ECONNREFUSED) - Unable to connect to API (ECONNRESET) - Unable to connect to API (ETIMEDOUT) + Connection refused — a firewall or proxy may be blocking it (ConnectionRefused) + Can't reach the API server — check your internet or DNS (ENOTFOUND) + No internet route — check your connection or VPN (EHOSTUNREACH) + Couldn't connect through your proxy (ERR_PROXY_TUNNEL) + Connection dropped (ECONNRESET) fetch failed Request timed out. Check your internet connection and proxy settings -Common causes include no internet access, a VPN that blocks `api.anthropic.com`, or a required corporate proxy that is not configured. **What to do:** +A code Claude Code doesn’t recognize appears as `Unable to connect to API` followed by the code in parentheses. Some of these messages can show more than one code: `Connection refused` can show `ConnectionRefused` or `ECONNREFUSED`, for example, and `Can't reach the API server` can show `ENOTFOUND` or `FailedToOpenSocket`. Before v2.1.227, each of these coded messages read `Unable to connect to API` followed by the code, for example `Unable to connect to API (ECONNREFUSED)`. Common causes include no internet access, a VPN that blocks `api.anthropic.com`, or a required corporate proxy that is not configured. **What to do:** * Confirm you can reach the API host from the same shell by running `curl -I https://api.anthropic.com`. On Windows PowerShell use `curl.exe -I https://api.anthropic.com` so the built-in `Invoke-WebRequest` alias is not used. * If you are behind a corporate proxy, set `HTTPS_PROXY` before launching Claude Code and see [Network configuration](</docs/en/network-config>) @@ -777,7 +925,7 @@ `Socket is closed` means the connection carrying a streaming response was closed while the response was still arriving. The most common cause is a corporate proxy on Windows dropping an established tunnel mid-response. Depending on how far the response had progressed, Claude Code retries the request, keeps what Claude produced, or ends the turn: * If Claude hasn’t completed any part of the response yet, including its thinking, Claude Code treats the failure as a dropped connection and retries the request automatically, so the turn continues, even if some text had started streaming. - * If Claude has finished thinking but hasn’t started any text or tool call, Claude Code re-issues the request up to two times in quick succession, then ends the turn with `Connection closed while thinking, before producing a response` if the connection keeps dropping at that point. + * If Claude has finished thinking but hasn’t started any text or tool call, Claude Code re-issues the request up to two times in quick succession, then ends the turn with `Connection lost before a response was produced` if the connection keeps dropping at that point. Before v2.1.227, that message read `Connection closed while thinking, before producing a response`. * If Claude has completed a block of text or a tool call, or has started one after finishing its thinking, but hasn’t finished the response, Claude Code keeps what Claude completed and shows an incomplete-response notice. It still runs any tool calls Claude completed and continues the turn from their results. * If the socket closes after Claude has finished the response, Claude Code ends the turn normally with the complete response. @@ -852,10 +1000,25 @@ Resuming with `claude --resume` or `claude --continue` reconnects to the [Remote Control](</docs/en/remote-control>) session recorded in that conversation. This message means the reconnection failed for a reason that may be temporary, such as a network interruption or a server error, so Claude Code can’t confirm whether the remote session still exists. Your local session keeps running without Remote Control. **What to do:** * Run `/remote-control` to retry the connection - * Start Claude Code without `--resume` to create a new Remote Control session + * Start a new session with `claude --remote-control` to create a new Remote Control session * For other Remote Control startup messages, see [Troubleshoot Remote Control](</docs/en/remote-control#troubleshooting>) -You won’t see this message when the server confirms the previous session no longer exists; Claude Code creates a new one in that case. Before v2.1.200, any reconnection failure created a new Remote Control session, which left extra sessions in the session list at claude.ai/code. +When the server reports instead that the previous session no longer exists, Claude Code shows [`Remote Control could not resume the previous session under the current login`](</docs/en/remote-control#remote-control-could-not-resume-the-previous-session-under-the-current-login>) rather than this message and doesn’t create a replacement session. Earlier versions created a new Remote Control session instead of showing a message: before v2.1.200 on any reconnection failure, and through v2.1.226 when the server reported the session gone. + +### + +​ + +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. + + Couldn't share the transcript. + +The upload must fit an 8 MiB limit. On a long session, Claude Code progressively drops parts of the share, the last request’s model settings first, then the structured conversation and subagent transcripts, and shows this message only when no reduced version can be sent or a network or server error stops the upload. When Claude Code saves a local archive instead, the message means it couldn’t write the archive. **What to do:** + + * Run `/feedback` to send the transcript with a description of what happened. See Report an error if `/feedback` is unavailable in your environment + * If other requests are failing too, check your network connection and see Unable to connect to API ## @@ -875,7 +1038,7 @@ Prompt is too long -**What to do:** +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. **What to do:** * Run `/compact` to summarize earlier turns and free space, or `/clear` to start fresh * Run `/context` to see a breakdown of what is consuming the window: system prompt, tools, memory files, and messages @@ -1006,7 +1169,7 @@ Claude Code sends beta-only fields such as `context_management` and `effort` alongside an `anthropic-beta` header that enables them. When a gateway forwards the body but drops the header, the API sees fields it doesn’t recognize. **What to do:** * Configure your gateway to forward the `anthropic-beta` header. See [feature pass-through](</docs/en/llm-gateway-protocol#feature-pass-through>) for what gateways must forward. - * As a fallback, set [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`](</docs/en/env-vars>) before launching. This disables features that require the beta header so requests succeed through a gateway that cannot forward it. + * 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. ### @@ -1072,10 +1235,10 @@ Model "claude-opus-4-8" is restricted by your organization's settings. Using claude-sonnet-4-6 instead. -Claude Code treats a model family alias, one of `opus`, `sonnet`, `haiku`, or `fable`, as a request for that family rather than for its newest version. On the Anthropic API and on [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), a restricted family alias resolves to the newest version of the family that your organization and the `availableModels` allowlist permit, and the substitution notice names that version. Claude Code rejects `/model <alias>` only when every version of the family is restricted. Before v2.1.205, a family alias was substituted or rejected based on its newest version alone, even when an older version of the same family was allowed. **What to do:** +A notice prefixed with an agent, skill, or command name means the restriction applied to that [subagent’s requested model](</docs/en/sub-agents#choose-a-model>): the subagent runs on the substituted model and your session’s model is unchanged. Before v2.1.223, Claude Code showed the notice only for subagents launched with the Agent tool. Claude Code treats a model family alias, one of `opus`, `sonnet`, `haiku`, or `fable`, as a request for that family rather than for its newest version. On the Anthropic API and on [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), a restricted family alias resolves to the newest version of the family that your organization and the `availableModels` allowlist permit, and the substitution notice names that version. Claude Code rejects `/model <alias>` only when every version of the family is restricted. Before v2.1.205, a family alias was substituted or rejected based on its newest version alone, even when an older version of the same family was allowed. **What to do:** * Run `/model` to pick from the models your organization allows. Restricted models are hidden from the picker. - * If the restricted model was set in `--model`, `ANTHROPIC_MODEL`, or the `model` field of a settings file, remove or update that value so the notice doesn’t recur on each launch + * If the restricted model was set in `--model`, `ANTHROPIC_MODEL`, the `model` field of a settings file, or the `model` frontmatter of a [subagent](</docs/en/sub-agents#choose-a-model>), skill, or command, remove or update that value so the notice doesn’t recur * If you need access to the restricted model, ask your organization admin to enable it. See [Organization model restrictions](</docs/en/model-config#organization-model-restrictions>). ### @@ -1282,6 +1445,42 @@ ​ +claude import is not yet available in this build + +You ran [`claude import`](</docs/en/cli-reference#cli-commands>), and Claude Code found the import flow turned off, so the command exits with code 1 instead of starting the import. Before v2.1.222, a build with the import flow off treated `import` as a prompt and started an interactive session instead of printing this message. + + `claude import` is not yet available in this build. Run `claude` and use /mcp or edit ~/.claude/settings.json directly. + +Claude Code turns `claude import` on through a feature flag it fetches from Anthropic and caches on disk. This message means the cached value is off. The cause is usually one of the following: + + * You haven’t started a session since installing, so Claude Code hasn’t fetched the flag yet. The first `claude import` can print this even when the feature is available to you. + * You use Claude Code through Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or Claude Platform on AWS. Claude Code doesn’t fetch feature flags on these providers, so `claude import` stays unavailable. + * You set `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, `DISABLE_GROWTHBOOK`, or [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars>), which turn off feature-flag fetching, so `claude import` stays unavailable. + +**What to do:** + + * On a fresh installation, start `claude`, wait for the session to load, exit, and run `claude import` again + * Where feature-flag fetching stays off, set the configuration up yourself: add MCP servers with [`claude mcp add`](</docs/en/mcp#installing-mcp-servers>), and create the [`CLAUDE.md` files](</docs/en/memory#how-claude-md-files-load>), [skills and commands](</docs/en/skills#where-skills-live>), and [subagents](</docs/en/sub-agents#choose-the-subagent-scope>) you want to carry over. The message also names `~/.claude/settings.json`. Of the configuration `claude import` carries, that file holds only the [permission mode](</docs/en/settings#permission-settings>); Claude Code doesn’t read MCP servers from it. + +### + +​ + +Could not read Claude Code config + +You ran [`claude import`](</docs/en/cli-reference#cli-commands>) while Claude Code couldn’t parse `~/.claude.json`, the file where it stores your login and per-project state. The subcommand reads that file to check availability but doesn’t show the recovery dialog the interactive session shows, so it exits with code 1. Before v2.1.222, `claude import` with an unreadable config file started an interactive session, whose recovery dialog handled the file. + + Could not read Claude Code config — run `claude` with no arguments to recover it. + +**What to do:** + + * Run `claude` with no arguments. Claude Code detects the invalid file and offers to reset it. Then run `claude import` again. + * To keep manual edits you’ve made, fix the JSON syntax in `~/.claude.json` in an editor instead, then rerun `claude import` + +### + +​ + Could not import a server from Claude Desktop Claude Code couldn’t add one of the servers you selected in `claude mcp add-from-claude-desktop`. The command still imports the other selected servers and prints one line per server it couldn’t add. Before v2.1.205, the first server that failed stopped the import and none of the selected servers were added. @@ -1322,7 +1521,12 @@ Use '--' to separate paths from revisions, like this: 'git <command> [<revision>...] -- [<file>...]' -The quoted command varies between runs: the review starts several `git` commands against `origin/HEAD` at once and reports whichever fails first, so you may see `git log` or a different `git diff` in its place. Git creates the ref only when the remote’s default branch is both advertised by the remote and covered by your fetch refspec. A full `git clone` of a remote with commits meets both conditions. Single-branch and CI checkouts fetch too narrow a refspec, a server-side HEAD left pointing at a branch nobody pushed advertises no default, and a repository with no `origin` remote, or one you never fetched, provides neither. **What to do:** +The quoted command varies between runs: the review starts several `git` commands against `origin/HEAD` at once and reports whichever fails first, so you may see `git log` or a different `git diff` in its place. Git creates the ref only when the remote’s default branch is both advertised by the remote and covered by your fetch refspec. A full `git clone` of a remote with commits meets both conditions. Single-branch and CI checkouts fetch too narrow a refspec, a server-side HEAD left pointing at a branch nobody pushed advertises no default, and a repository with no `origin` remote, or one you never fetched, provides neither. Claude Code shows the same error for any skill that [injects dynamic context](</docs/en/skills#when-an-injected-command-fails>). A failed injected command aborts that skill’s invocation. Two sibling strings fire before the command runs at all: + + * `Shell command permission check failed for pattern "..."`: the command’s permission check returned something other than allow. Injected commands never prompt, so the invocation aborts without asking you. Pre-approve commands that would otherwise hit the default permission prompt with [`allowed-tools`](</docs/en/skills#pre-approve-tools-for-a-skill>). A matching ask or deny rule still aborts the invocation regardless of `allowed-tools` + * `Skill <name> requires bash (`shell: bash` in frontmatter) but Git Bash was not found`: the skill’s frontmatter demands bash on a machine without it. Install Git for Windows or change the frontmatter to `shell: powershell`. See [How injected commands run](</docs/en/skills#how-injected-commands-run>) + +**What to do:** * Create the ref by naming your remote’s default branch: `git remote set-head origin <default-branch>`. This works whenever the local tracking ref `origin/<default-branch>` exists. If it doesn’t, as in single-branch clones, fetch the branch first: run `git remote set-branches --add origin <branch>`, then `git fetch origin`, then rerun the set-head command. Rerun `/security-review`. * If you’d rather not name the branch, run `git fetch origin` and then `git remote set-head origin --auto`, which asks the remote which branch is its default. It fails with `error: Cannot determine remote HEAD` when the remote advertises no default branch, because it is empty or its HEAD points at a branch nobody pushed; name the branch explicitly instead. It fails with `error: Not a valid ref` when your clone doesn’t fetch that branch; widen the refspec as above first. @@ -1408,6 +1612,28 @@ * Run `claude --resume <session-id>` with the session ID from the message to retry * If the retry fails again, run `claude` to start a new session + +### + +​ + +No conversation found with the session ID + +You passed a session ID to `claude --resume <session-id>` and no saved transcript matched it: + + No conversation found with session ID: <session-id> + +Claude Code exits with code 1 after showing the message. Claude Code [searches the current project first, then every other project on this machine](</docs/en/sessions#resume-a-session>) for the ID. Before v2.1.223, the lookup stopped at the current project directory and its git worktrees, so resume from the directory the session last worked in. Common causes: + + * **Mistyped ID** : for a non-interactive run, the ID is the `session_id` field of the [`--output-format json` output](</docs/en/headless#get-structured-output>) + * **Deleted transcript** : Claude Code removes transcripts after the [retention period](</docs/en/sessions#where-transcripts-are-stored>), 30 days by default, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>) + * **Different machine** : Claude Code stores transcripts locally, so resume the session on the machine where it ran + * **Duplicate copies** : if you copied a project directory under `~/.claude/projects` so two transcripts carry the same ID, Claude Code reports this message rather than resume one copy arbitrarily + +**What to do:** + + * For an interactive session, open the [session picker](</docs/en/sessions#use-the-session-picker>) with `claude --resume` and press `Ctrl+A` to widen it to every project on this machine, then select the session + * Sessions created with `claude -p` or the [Agent SDK](</docs/en/agent-sdk/overview>) don’t appear in the picker, so re-check the ID against the `session_id` your original run printed ## @@ -1515,14 +1741,14 @@ File is covered by a Read deny rule -The Edit tool was called on a path matched by a [`Read` deny rule](</docs/en/permissions#read-and-edit>), including creating a new file at that path. Editing rewrites content Claude has to be able to read back, so the call is refused before any file access. The rule blocks the Edit tool only: Write and NotebookEdit aren’t covered by `Read` deny rules. Before v2.1.208, only an `Edit` deny rule blocked edits, and a `Read` deny rule alone didn’t. +The Edit or Write tool was called on a path matched by a [`Read` deny rule](</docs/en/permissions#read-and-edit>), including creating a new file at that path. Both tools change content Claude has to be able to read back, so Claude Code refuses the call before any file access. NotebookEdit isn’t covered by `Read` deny rules. Before v2.1.228, the rule blocked the Edit tool only, and before v2.1.208, only an `Edit` deny rule blocked edits. File is covered by a Read deny rule in your permission settings and cannot be edited. -**What to do:** - - * If Claude should be able to edit the file, remove or narrow the `Read` deny rule in `/permissions` or in [settings](</docs/en/settings#permission-settings>) - * If the file must stay untouched, keep the rule and add an `Edit` deny rule for the same path so the Write and NotebookEdit tools are blocked too +When Claude Code refuses the Write tool, the message ends `and cannot be written` instead. **What to do:** + + * If Claude should be able to change the file, remove or narrow the `Read` deny rule in `/permissions` or in [settings](</docs/en/settings#permission-settings>) + * If the file must stay untouched, keep the rule and add an `Edit` deny rule for the same path to block the NotebookEdit tool too ### @@ -1554,13 +1780,34 @@ * Narrow the pattern so it matches only the intended process, for example the full path of the target binary rather than a short substring * To stop processes started by the current shell, use `pkill -P $$` with the pattern, which limits the match to the shell’s own child processes +### + +​ + +Failed to write to a teammate’s inbox + +Claude Code couldn’t write a message to a teammate’s mailbox file under `~/.claude/teams/{team-name}/inboxes/`, so the recipient received nothing. The write fails when Claude Code can’t create or update the file, for example because the disk is full, the directory isn’t writable, or another agent holds the inbox lock for too long. Before v2.1.224, Claude Code reported the message as sent even when the write failed. The error appears in the sending agent’s tool result rather than as a banner in your terminal, and its text tells Claude to try again: + + Failed to write to researcher's inbox — nothing was sent. Try again, or message the lead. + +Structured [agent team](</docs/en/agent-teams>) protocol messages fail the same way, and the error names the undelivered message: when Claude Code can’t write a plan approval, plan rejection, shutdown request, or shutdown rejection, the error reads `Failed to write the <message> to <name>'s inbox — nothing was sent`. The `plan approval` in that list is the lead’s decision approving a teammate’s plan; the teammate’s plan submission is the separate `plan approval request` message. That message and two other protocol messages carry their own message text and consequence: + + * `Failed to write the plan approval request to the lead's inbox — plan not submitted; try again`: the teammate’s plan never reached the lead, and the teammate stays in plan mode until a resubmission succeeds + * `The permission request could not be delivered to the team lead (mailbox write failed)`: the teammate’s permission request never reached the lead, so nobody approved the tool call + * `The confirmation could not be written to team-lead's inbox.`: the shutdown approval itself took effect and the teammate exits; only the confirmation to the lead is missing + +When you message a teammate yourself, typing `@name` followed by the message in the lead session, the same failure appears as a notification, `Couldn't write to @name's inbox — message not sent. Try again.`, and Claude Code keeps your text in the prompt box so you can send it again. **What to do:** + + * Ask the sender to resend the message; contention for the inbox lock is transient and clears on retry + * Check free disk space, and check that `~/.claude/teams` and the files under it are writable by your user + ## ​ Background session errors -[Background sessions](</docs/en/agent-view>) run without an interactive terminal of their own, so commands that need one behave differently there. These messages appear in the transcript of a background session, in the terminal that attaches to one, or in the session or shell you dispatch from; where a message is specific to one surface, its entry says so. +[Background sessions](</docs/en/agent-view>) run without an interactive terminal of their own, so commands that need one behave differently there. These messages appear in the transcript of a background session, in the terminal that attaches to one, in the session or shell you dispatch from, or, for the worktree-guard entries below, in any session isolated in a worktree or running a worktree-isolated subagent; where a message is specific to one surface, its entry says so. ### @@ -1576,6 +1823,36 @@ * Attach to the session from agent view, where it’s listed under **Needs input** , and run the command again * Or use the form the message names, such as `/mcp reconnect <server>`, `/mcp enable`, or `/mcp disable`, which work without attaching + +### + +​ + +Write or command blocked because the path cannot be safely resolved + +Claude addressed a file or working directory through a spelling that the [worktree-isolation guard](</docs/en/agent-view#how-file-edits-are-isolated>) can’t resolve to one verifiable location. The guard checks writes and command working directories in [any session isolated in a worktree](</docs/en/worktrees#how-claude-code-enforces-isolation>), interactive or background, and in [worktree-isolated subagents](</docs/en/worktrees#isolate-subagents-with-worktrees>). It resolves symlinks before checking that the operation doesn’t reach the shared checkout, and when resolution fails, it blocks the operation rather than letting it land there. The message names the path forms it refuses and how to retry: + + This write was blocked because the path is spelled in a form that cannot be safely resolved (for example through a symlink storing a raw dot segment, a network-share or device-namespace shape, or an unreadable ancestor directory). If the file is inside the worktree /path/to/worktree, address it by its direct symlink-free path instead. + +A blocked command reports the same cause for its working directory and ends with `re-run the command from its direct symlink-free path`. Before v2.1.217, the guard compared path spellings without resolving symlinks, so these spellings weren’t blocked and a write routed through a symlink could land in the shared checkout. **What to do:** + + * Usually nothing: the full message goes to Claude as a tool error, and Claude retries with the direct path it names. For a blocked file edit, the conversation view shows only a short `Error editing file` line; the full message appears in the transcript view, which you open with `Ctrl+O`. A blocked command prints it in its command output. + * If the block repeats on the same file, the path likely runs through a committed symlink whose target contains `..`, such as `docs/current -> ../README.md`; ask Claude to edit the target file by its real path instead of through the link + +### + +​ + +Write or command blocked because the path names a network location + +Claude addressed a file or working directory through a path that names a drive that isn’t on your machine, a UNC share such as `\\server\share\file` or a `/net` automount path, while the session’s checkout is on a local disk. The same worktree-isolation guard can’t verify that such a path stays out of the shared checkout, so it blocks the operation. Isolating the session in a worktree doesn’t lift the block. The message names the form of path to use instead: + + This write was blocked because the path is network-shaped (a UNC share or /net automount spelling) while this session's checkout is local. Isolating cannot unblock it. If the file is genuinely inside the worktree /path/to/worktree, address it by its local, plainly-spelled path instead. + +A blocked command reports the same cause for its working directory and ends with `re-run the command from its local, plainly-spelled path`. Before v2.1.217, the guard compared path text only, so addressing a file inside the checkout through a UNC or `/net` path wasn’t blocked. **What to do:** + + * Usually nothing: Claude retries with the local spelling the message asks for + * If the file genuinely lives on a network share, it’s outside the session’s local workspace; edit it from a regular interactive session instead ### @@ -1710,6 +1987,66 @@ * Identify which files were skipped so you can handle each one with the steps below. The message gives only a count; the debug log at `~/.claude/debug/<session-id>.txt` names each skipped path as the restore runs, so turn on debug logging with `/debug` before your next restore. On macOS or Linux, you can instead find the links directly: `find . -type l` for symlinks and `find . -type f -links +1` for hard-linked files. * If a skipped file is a link you created on purpose, such as a config file managed by a dotfile manager or a file hard-linked by tools like pnpm, the rewind left its contents alone. To undo the session’s changes to it, ask Claude to reverse the edit or edit the file yourself * If you didn’t create the link, inspect the path before trusting its contents: something replaced the file after the checkpoint + +## + +​ + +Session saving warnings + +Claude Code shows these warnings on a persistent line below the input box when it isn’t saving your session transcript. The session keeps working either way; the warnings tell you the session may be missing from [`--resume`](</docs/en/sessions>) later. + +### + +​ + +Transcript writes are failing + +Claude Code saves the transcript to disk as you work, and its writes to [the transcript file](</docs/en/sessions#where-transcripts-are-stored>) are failing. The message names the cause with the underlying error code, for example a full disk: + + Transcript writes are failing (disk full — ENOSPC) · recent messages may not be saved for resume + +The warning appears at different points depending on the error: + + * On the first failure for conditions that don’t clear on their own: a full disk, an exceeded disk quota, a read-only filesystem, a path over the filesystem’s length limit, or, on macOS and Linux, a permission error + * After repeated failures spanning at least a minute for everything else, including permission errors on Windows, where an antivirus scan can fail a single write that then succeeds on retry + +Before v2.1.217, Claude Code dropped the failing writes without a warning, and a later `--resume` missing recent messages was the first sign. **What to do:** + + * Fix the condition the error code names: free disk space for `ENOSPC`; raise or clear the quota for `EDQUOT`; restore write access to the transcript location for `EACCES`, `EPERM`, or `EROFS` + * The warning clears on its own at the next successful write; no restart is needed + * Messages sent while the warning was showing may still be missing when you resume the session later + +### + +​ + +Transcript saving is off because CLAUDE_CODE_SKIP_PROMPT_HISTORY is set + +This session started with [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>) set, so Claude Code writes no transcript or prompt history for it: + + Transcript saving is off — CLAUDE_CODE_SKIP_PROMPT_HISTORY is set · --resume will not find this session; if unintended, unset it and restart + +The variable is an intentional opt-out for ephemeral scripted sessions, but it can also reach a session through a shell profile, a wrapper script, or a parent process that exported it. **What to do:** + + * If you set the variable on purpose, no action is needed; the notice confirms the session won’t appear in `--resume`, `--continue`, or up-arrow history + * If you didn’t, remove the variable from the shell or script that launches `claude`, then start a new session. Messages from the current session aren’t saved retroactively. + +### + +​ + +Transcript saving is off because of an inherited CLAUDE_CODE_CHILD_SESSION marker + +Claude Code sets [`CLAUDE_CODE_CHILD_SESSION`](</docs/en/env-vars>) in the subprocesses it spawns, and treats an interactive session that inherits it as nested: Claude Code saves no transcript for it, so sessions that Claude itself starts don’t fill your `--resume` list. This notice means your current session inherited the marker: + + Transcript saving is off — inherited CLAUDE_CODE_CHILD_SESSION marker · restart with CLAUDE_CODE_FORCE_SESSION_PERSISTENCE=1 to keep future transcripts + +The notice is expected when you ran `claude` from inside another Claude Code session; it signals a misclassification when the marker leaked through a long-lived intermediary, for example a terminal, `screen` session, or launcher that a Claude Code session originally started. Inside tmux, Claude Code detects a marker that arrived through the tmux server’s global environment and keeps saving, so this notice doesn’t appear for that case. **What to do:** + + * If you started this session from inside another Claude Code session on purpose, no action is needed + * If this is a top-level session, exit and restart with [`CLAUDE_CODE_FORCE_SESSION_PERSISTENCE=1`](</docs/en/env-vars>) set. Saving applies from the restart, so messages sent before it aren’t saved. + * To fix future launches from the same terminal or launcher, remove `CLAUDE_CODE_CHILD_SESSION` from its environment ## @@ -1755,6 +2092,29 @@ In a [background session](</docs/en/agent-view>) or with `--output-format json` or `stream-json`, Claude Code writes the warning to the debug log instead of stderr, so machine-read output stays clean; run with `--debug` to capture it at `~/.claude/debug/<session-id>.txt`. Before v2.1.210, Claude Code accepted these rules without a 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. + + CLAUDE_CODE_DISABLE_1M_CONTEXT is set, but the 200K limit isn't enforced for <model>, so this session can grow past it. To enforce it, set CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000 (or the autoCompactWindow setting). + +Claude Code enforces the 200K limit on its own for every model it recognizes as having a native 1M window, and for model IDs it doesn’t recognize it compacts at the window it assumes. The warning appears when other configuration defeats that enforcement: + + * The model ID isn’t one Claude Code recognizes, such as an [LLM gateway](</docs/en/llm-gateway>) alias, and you set [`CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT=1`](</docs/en/env-vars>) or raised the assumed window past 200K with [`CLAUDE_CODE_MAX_CONTEXT_TOKENS`](</docs/en/env-vars>). In this case the message also offers `or update to a Claude Code version that recognizes <model>` as a remedy. + * A `context-1m` beta requested through [`ANTHROPIC_BETAS`](</docs/en/env-vars>) or the [`--betas`](</docs/en/cli-reference#cli-flags>) flag still asks the API for the 1M window on a model that accepts that beta, while nothing compacts the session at 200K + +**What to do:** + + * Set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000`](</docs/en/env-vars>), or the [`autoCompactWindow`](</docs/en/settings#available-settings>) setting to `200000`, so auto-compaction compacts at the 200K boundary + * If the message names a model ID this version doesn’t recognize, run `claude update`. A version that recognizes the ID as a 1M-context model enforces the limit without further configuration. + * If you want the session to use the model’s full window instead, unset `CLAUDE_CODE_DISABLE_1M_CONTEXT`; the warning reports only that the 200K limit isn’t enforced + +In a [background session](</docs/en/agent-view>) or with `--output-format json` or `stream-json`, Claude Code writes the warning to the debug log instead of stderr. + ## ​
modified Speed up responses with fast mode View current →
--- a/fast-mode.md +++ b/fast-mode.md @@ -4,7 +4,7 @@ * Use `/fast` to toggle on fast mode in the Claude Code CLI. Fast mode is not supported in the VS Code extension. * Fast mode pricing per MTok input/output is $10/$50 on Opus 5 and Opus 4.8. - * Available to all Claude Code users on subscription plans (Pro/Max/Team/Enterprise) and Claude Console. + * Available to Claude Code users on subscription plans (Pro/Max/Team/Enterprise) and on Claude Console. Team and Enterprise organizations need an Owner to enable it first, and Console organizations need access provisioned first, both described under Requirements. * For Claude Code users on subscription plans (Pro/Max/Team/Enterprise), fast mode is available via usage credits only and not included in the subscription rate limits. ## @@ -25,7 +25,7 @@ * A small `↯` icon appears next to the prompt while fast mode is active * Run `/fast` again at any time to check whether fast mode is on or off -Opus 5 is the fast mode default in Claude Code v2.1.219 and later. Before v2.1.219, fast mode defaulted to Opus 4.8 on v2.1.154 through v2.1.218, and to Opus 4.7 on v2.1.142 through v2.1.153. When you disable fast mode with `/fast` again, you remain on Opus. The model does not revert to your previous model. To switch to a different model, use `/model`. +Opus 5 is the fast mode default in Claude Code v2.1.219 and later. Before v2.1.219, fast mode defaulted to Opus 4.8 on v2.1.154 through v2.1.218, and to Opus 4.7 on v2.1.142 through v2.1.153. When you disable fast mode with `/fast` again, you remain on Opus. To switch to a different model, use `/model`. ### @@ -36,9 +36,9 @@ Fast mode follows your model switches in both directions: * **Switch away** : when you switch to a model that doesn’t support fast mode, Claude Code turns fast mode off. This includes Opus 4.7; before v2.1.221, fast mode stayed on after a switch to Opus 4.7 and the API rejected the requests. - * **Switch back** : switching back to a supported Opus model turns fast mode on again when your saved fast mode preference is on, the same preference a new session starts from by default. A model switch never turns fast mode on for a session whose saved preference is off, and with per-session opt-in configured, switching back doesn’t turn it on either; run `/fast` to re-enable it. Before v2.1.208, fast mode stayed off after you switched back until you ran `/fast` again. - -Whenever a model switch turns fast mode on or off, Claude Code shows a `Fast mode ON` or `Fast mode OFF` confirmation, and the `↯` icon appears while fast mode is on. This holds whether you switch with `/model`, with [`/config model=<model>`](</docs/en/settings>), or from a device connected through [Remote Control](</docs/en/remote-control>); before v2.1.218, switches through `/config model=<model>` or Remote Control changed fast mode without the confirmation. Claude Code resends the session’s fast mode status to devices connected through Remote Control after a model switch, a reconnection, or a failed availability check. + * **Switch back** : switching back to a supported Opus model turns fast mode on again when your saved fast mode preference is on, the same preference a new session starts from by default. A model switch never turns fast mode on for a session whose saved preference is off, and with per-session opt-in configured, switching back doesn’t turn it on either; run `/fast` to re-enable it. + +Whenever a model switch turns fast mode on or off, Claude Code shows a `Fast mode ON` or `Fast mode OFF` confirmation, and the `↯` icon appears while fast mode is on. This holds whether you switch with `/model`, with [`/config model=<model>`](</docs/en/settings>), or from a device connected through [Remote Control](</docs/en/remote-control>). Claude Code resends the session’s fast mode status to devices connected through Remote Control after a model switch, a reconnection, or a failed availability check. ## @@ -108,10 +108,10 @@ Fast mode requires all of the following: - * **Anthropic API or subscription only** : fast mode is available through the Anthropic Console API and for Claude subscription plans using usage credits. It is not available on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or Claude Platform on AWS. + * **Anthropic API or subscription only** : fast mode is available through the Anthropic Console API and for Claude subscription plans using usage credits. It is not available on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or Claude Platform on AWS. Console organizations must also have fast mode access provisioned. * **Usage credits turned on for subscription plans** : on a Pro, Max, Team, or Enterprise plan, your account must have [usage credits](</docs/en/costs#add-usage-credits-to-your-subscription>) turned on, which allows billing beyond your plan’s included usage. Until they’re on, `/fast` shows “Fast mode requires usage credits · /usage-credits to turn them on”. On Pro and Max, turn them on in the **Usage credits** section of [**Settings > Usage**](<https://claude.ai/settings/usage>) on claude.ai, or run `/usage-credits` to open that page. On Team and Enterprise, a member with billing access turns them on for the organization at [**Admin settings > Usage**](<https://claude.ai/admin-settings/usage>), and a member without it runs `/usage-credits` to send the organization’s admins a request. -Fast mode usage draws directly from usage credits, even if you have remaining usage on your plan. This means fast mode tokens do not count against your plan’s included usage and are charged at the fast mode rate from the first token. +Fast mode usage draws directly from usage credits, even if you have remaining usage on your plan. * **Paid Console organization** : Claude Console accounts don’t use usage credits, and your organization pays for fast mode per token with the rest of its API usage. On the Console’s free Evaluation plan, `/fast` shows “Fast mode unavailable during evaluation. Please purchase credits.” To clear it, purchase credits in your [Console billing settings](<https://platform.claude.com/settings/billing>). * **Owner enablement for Team and Enterprise** : fast mode is disabled by default for Team and Enterprise organizations. An Owner must explicitly enable fast mode before users can access it. @@ -126,7 +126,7 @@ Where you enable fast mode depends on which product your organization uses: - * **Console** (API customers): an admin enables it in [Claude Code preferences](<https://platform.claude.com/claude-code/preferences>) + * **Console** (API customers): an admin enables it in [Claude Code preferences](<https://platform.claude.com/claude-code/preferences>). Fast mode is in research preview, so your organization must also have fast mode access provisioned before fast mode requests succeed. To get access, contact your account manager or join the waitlist, as described in [fast mode on the Claude API](<https://platform.claude.com/docs/en/build-with-claude/fast-mode>). Without provisioned access, the API rejects each fast mode request with a 429, and Claude Code treats each rejection as a fast mode rate limit. Unlike a rate limit’s cooldown, the rejections continue until access is provisioned. * **Claude AI** (Team and Enterprise): an Owner enables it at [Admin Settings > Claude Code](<https://claude.ai/admin-settings/claude-code>) Another option to disable fast mode entirely is to set `CLAUDE_CODE_DISABLE_FAST_MODE=1`. See [Environment variables](</docs/en/env-vars>). @@ -155,13 +155,13 @@ Require per-session opt-in -By default, fast mode a user turns on in an interactive session persists across sessions: it stays on in future sessions. To change this, set `fastModePerSessionOptIn` to `true` in any [settings file](</docs/en/settings#settings-files>), which causes each session to start with fast mode off and requires users to explicitly enable it with `/fast`. Owners on [Team](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=fast_mode_teams#team-&-enterprise>) or [Enterprise](<https://anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=fast_mode_enterprise>) plans can deploy it organization-wide through [server-managed settings](</docs/en/server-managed-settings>). +By default, fast mode a user turns on in an interactive session persists across sessions. To change this, set `fastModePerSessionOptIn` to `true` in any [settings file](</docs/en/settings#settings-files>), which causes each session to start with fast mode off and requires users to explicitly enable it with `/fast`. Owners on [Team](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=fast_mode_teams#team-&-enterprise>) or [Enterprise](<https://anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=fast_mode_enterprise>) plans can deploy it organization-wide through [server-managed settings](</docs/en/server-managed-settings>). { "fastModePerSessionOptIn": true } -This is useful for controlling costs in organizations where users run multiple concurrent sessions. Users can still enable fast mode with `/fast` when they need speed, but it resets at the start of each new session. The user’s fast mode preference is still saved, so removing this setting restores the default persistent behavior. +This is useful for controlling costs in organizations where users run multiple concurrent sessions. The user’s fast mode preference is still saved, so removing this setting restores the default persistent behavior. ##
modified Feature availability View current →
--- a/feature-availability.md +++ b/feature-availability.md @@ -34,7 +34,7 @@ * **MCP servers** : [connectors from claude.ai](</docs/en/mcp#use-mcp-servers-from-claude-ai>) load only when your claude.ai subscription is the active authentication method. [Tool search](</docs/en/mcp#configure-tool-search>) is off by default when `ANTHROPIC_BASE_URL` points to a non-first-party host, and isn’t supported on Google Cloud’s Agent Platform models earlier than the Claude 4.5 generation or on Microsoft Foundry [deployments hosted on Azure](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>) * **Subagents** : the built-in [Explore subagent](</docs/en/sub-agents#built-in-subagents>) caps its inherited model at Opus on the Claude API, and inherits the main conversation’s model directly on any other provider, including Claude Platform on AWS - * **[Commands](</docs/en/commands#all-commands>)** : `/design-sync` and `/radio` are unavailable on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and Claude Platform on AWS, `/voice` requires a claude.ai account, and `/list-agents` and its alias `/peers` are available only in sessions where [cross-session messaging is enabled](</docs/en/cross-session-messaging#availability>) + * **[Commands](</docs/en/commands#all-commands>)** : `/design-sync`, `/import` with its `claude import` subcommand form, and `/radio` are unavailable on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and Claude Platform on AWS, `/voice` requires a claude.ai account, and `/list-agents` and its alias `/peers` are available only in sessions where [cross-session messaging is enabled](</docs/en/cross-session-messaging#availability>) ### @@ -66,7 +66,7 @@ These features work in the local CLI but depend on a server-side capability that not every provider exposes. Feature| Claude subscription| Anthropic Console| Amazon Bedrock| Claude Platform on AWS| Google Cloud’s Agent Platform| Microsoft Foundry ---|---|---|---|---|---|--- [Web search](</docs/en/tools-reference#websearch-tool-behavior>)| ✓| ✓| ✗| ✓| See note 1| ✓ ([deployments hosted on Anthropic](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>)) -[Fast mode](</docs/en/fast-mode>)| ✓| ✓| ✗| ✗| ✗| ✗ +[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>)| ✓ (macOS and Linux) 6| ✓ (macOS and Linux) 6| ✗| ✗| ✗| ✗ @@ -91,7 +91,7 @@ 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. WSL 2 counts as Linux; native Windows isn’t supported. With API key authentication, same-machine messaging only. Reaching your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions requires [cloud access](</docs/en/cross-session-messaging#see-which-sessions-claude-can-reach>), and reaching your sessions on other machines requires meeting the [Remote Control requirements](</docs/en/remote-control#requirements>); both need a claude.ai sign-in. See [Message sessions on other machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>). +6 Requires Claude Code v2.1.224 or later. WSL 2 counts as Linux; native Windows isn’t supported. 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>). 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,42 +113,46 @@ * 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` 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>), [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:** * [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 + * [`/code-review`](</docs/en/code-review#let-claude-start-the-review>): runs when you type it; Claude doesn’t start it on its own * [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. -**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` 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 +**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:** + + * [`/loop`](</docs/en/scheduled-tasks>): explicit intervals only + * [`/code-review`](</docs/en/code-review#let-claude-start-the-review>): runs when you type it; Claude doesn’t start it on its own **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>). -**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` 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>), [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:** * [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 + * [`/code-review`](</docs/en/code-review#let-claude-start-the-review>): runs when you type it; Claude doesn’t start it on its own * [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>). -**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` 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>), [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:** * [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 + * [`/code-review`](</docs/en/code-review#let-claude-start-the-review>): runs when you type it; Claude doesn’t start it on its own * [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>). -**Not available:** all features that require a Claude subscription.Everything in CLI capabilities that vary by provider is available, as are [server-managed settings](</docs/en/server-managed-settings>) when the API key belongs to a Team or Enterprise organization. +**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. ##
modified Fullscreen rendering View current →
--- a/fullscreen.md +++ b/fullscreen.md @@ -10,7 +10,7 @@ Enable fullscreen rendering -Run `/tui fullscreen` inside any Claude Code conversation. The CLI saves the [`tui` setting](</docs/en/settings#available-settings>) and relaunches into fullscreen with your conversation intact, so you can switch mid-session without losing context. Run `/tui default` to switch back to the classic renderer, or `/tui` with no argument to print which renderer is active. In [screen reader mode](</docs/en/accessibility>), Claude Code always uses the classic renderer except in attached [background sessions](</docs/en/agent-view>), which still render fullscreen. If you run `/tui fullscreen` in any other session, Claude Code prints an explanation instead of switching and doesn’t change the saved `tui` setting. The relaunched session keeps the conversation as it appears on screen. If you ran [`/rewind`](</docs/en/checkpointing#rewind-and-summarize>) earlier in the session, the relaunch resumes from the rewound point rather than the longer transcript saved on disk. Before v2.1.207, switching renderers after a rewind restored the conversation the rewind had removed. You can also set the `CLAUDE_CODE_NO_FLICKER` environment variable before starting Claude Code: +Run `/tui fullscreen` inside any Claude Code conversation. The CLI saves the [`tui` setting](</docs/en/settings#available-settings>) and relaunches into fullscreen with your conversation intact, so you can switch mid-session without losing context. Run `/tui default` to switch back to the classic renderer, or `/tui` with no argument to print which renderer is active. In [screen reader mode](</docs/en/accessibility>), Claude Code always uses the classic renderer except in attached [background sessions](</docs/en/agent-view>), which still render fullscreen. If you run `/tui fullscreen` in any other session, Claude Code prints an explanation instead of switching and doesn’t change the saved `tui` setting. The relaunched session keeps the conversation as it appears on screen. If you ran [`/rewind`](</docs/en/checkpointing#rewind-and-summarize>) earlier in the session, the relaunch resumes from the rewound point rather than the longer transcript saved on disk. If you rewound to before your first message, the relaunched session starts empty. You can also set the `CLAUDE_CODE_NO_FLICKER` environment variable before starting Claude Code: CLAUDE_CODE_NO_FLICKER=1 claude @@ -45,8 +45,8 @@ * **Click an option in a select menu** to choose it. This covers permission prompts, `/model`, `/config`, and other dialogs that show a list of options. Hovering shows a pointer on the row under your cursor. Requires Claude Code v2.1.187 or later. * **Click an option in a multi-select menu** to toggle it, and click the submit button to confirm your choices. Clicking a free-text row, such as the `Other` row in a multiple-choice question, focuses its input field so you can type an answer. Requires Claude Code v2.1.208 or later. * **Click a collapsed tool result** to expand it and see the full output. Click again to collapse. The tool call and its result expand together. Only messages that have more to show are clickable. - * **Hold`Cmd` on macOS, or `Ctrl` on Linux and Windows, and click a URL or file path** to open it. File paths in tool output, like the ones printed after an Edit or Write, open in your default application. Plain `http://` and `https://` URLs open in your browser. As of v2.1.181, a plain click without holding `Cmd` or `Ctrl` no longer opens links, matching native terminal behavior. Some macOS terminals forward `Cmd`+click to the running app instead of opening the link themselves, and the terminal mouse protocol has no way to encode the `Cmd` key, so Claude Code receives it as a plain click. In Ghostty, and as of v2.1.198 in Warp on macOS, Claude Code detects this and lets a plain click on a link open it, and holding `Cmd` still works. In the VS Code integrated terminal and similar xterm.js-based terminals, Claude Code defers to the terminal’s own link handler, which uses the same gesture. - * **Click and drag** to select text anywhere in the conversation. Double-click selects a word, matching iTerm2’s word boundaries so a file path selects as one unit. As of v2.1.198, double-clicking a URL selects the whole URL, including the scheme. Triple-click selects the line. + * **Hold`Cmd` on macOS, or `Ctrl` on Linux and Windows, and click a URL or file path** to open it. File paths in tool output, like the ones printed after an Edit or Write, open in your default application. Plain `http://` and `https://` URLs open in your browser. A plain click without holding `Cmd` or `Ctrl` doesn’t open links, matching native terminal behavior. Some macOS terminals forward `Cmd`+click to the running app instead of opening the link themselves, and the terminal mouse protocol has no way to encode the `Cmd` key, so Claude Code receives it as a plain click. In Ghostty, and in Warp on macOS, Claude Code detects this and lets a plain click on a link open it, and holding `Cmd` still works. In the VS Code integrated terminal and similar xterm.js-based terminals, Claude Code defers to the terminal’s own link handler, which uses the same gesture. + * **Click and drag** to select text anywhere in the conversation. Double-click selects a word, matching iTerm2’s word boundaries so a file path selects as one unit. Double-clicking a URL selects the whole URL, including the scheme. Triple-click selects the line. * **Scroll with the mouse wheel** to move through the conversation. Selected text copies to your clipboard automatically on mouse release. To turn this off, toggle Copy on select in `/config`. With Copy on select off, press `Ctrl+Shift+c` to copy manually. On terminals that support the kitty keyboard protocol, such as kitty, WezTerm, Ghostty, and iTerm2, `Cmd+c` also works. If you have a selection active, `Ctrl+c` copies instead of cancelling. With a selection active, hold `Shift` and press the arrow keys to extend it from the keyboard. `Shift+↑` and `Shift+↓` scroll the viewport when the selection reaches the top or bottom edge. `Shift+Home` and `Shift+End` extend to the start or end of the current line. @@ -80,7 +80,7 @@ Auto-follow -Scrolling up pauses auto-follow so new output doesn’t pull you back to the bottom. A `Jump to bottom` button floats over the bottom edge of the transcript while you’re scrolled up, and shows a count such as `3 new messages` when new output arrives. Click it, press `Ctrl+End`, or scroll to the bottom to resume following. While auto-follow is paused, the view also stays where you scrolled it when a response finishes streaming. Before v2.1.207, the view could jump above the start of the answer when a long response finished streaming. The button’s keyboard hint reflects what your keyboard can send. On macOS it suggests clicking, or `Fn+↓` to scroll, because `Ctrl+End` doesn’t reach Claude Code from a Mac keyboard. Rebind [`scroll:bottom`](</docs/en/keybindings#scroll-actions>) and the button shows your chord on every platform. Before v2.1.206, the button suggested `Ctrl+End` on macOS. On a terminal too narrow for the full label, the button shortens the hint instead of wrapping onto the transcript row underneath. Before v2.1.206, a long label could wrap over the transcript. To turn auto-follow off entirely so the view stays where you leave it, open `/config` and set Auto-scroll to off. With auto-scroll disabled, the view never jumps to the bottom on its own. Permission prompts and other dialogs that need a response still scroll into view regardless of this setting. +Scrolling up pauses auto-follow so new output doesn’t pull you back to the bottom. A `Jump to bottom` button floats over the bottom edge of the transcript while you’re scrolled up, and shows a count such as `3 new messages` when new output arrives. Click it, press `Ctrl+End`, or scroll to the bottom to resume following. While auto-follow is paused, the view also stays where you scrolled it when a response finishes streaming. The button’s keyboard hint reflects what your keyboard can send. On macOS it suggests clicking, or `Fn+↓` to scroll, because `Ctrl+End` doesn’t reach Claude Code from a Mac keyboard. Rebind [`scroll:bottom`](</docs/en/keybindings#scroll-actions>) and the button shows your chord on every platform. On a terminal too narrow for the full label, the button shortens the hint instead of wrapping onto the transcript row underneath. To turn auto-follow off entirely so the view stays where you leave it, open `/config` and set Auto-scroll to off. With auto-scroll disabled, the view never jumps to the bottom on its own. Permission prompts and other dialogs that need a response still scroll into view regardless of this setting. ### @@ -126,8 +126,6 @@ * **`[`** : writes the full conversation into your terminal’s native scrollback buffer, with all tool output expanded. The conversation is now ordinary text in your terminal, so `Cmd+f`, tmux copy mode, and any other native tool can search or select it. Long sessions may pause for a moment while this happens. This lasts until you exit transcript mode with `Esc` or `q`, which returns you to fullscreen rendering. The next `Ctrl+o` starts fresh. * **`v`** : writes the conversation to a temporary file and opens it in `$VISUAL` or `$EDITOR`. -Press `Esc` or `q` to return to the prompt. - ## ​
modified Claude Code GitLab CI/CD View current →
Show diff (293 lines)
--- a/gitlab-ci-cd.md +++ b/gitlab-ci-cd.md @@ -84,6 +84,8 @@ - apk update - apk add --no-cache git curl bash - curl -fsSL https://claude.ai/install.sh | bash + # The installer places claude in ~/.local/bin, which isn't on PATH in this image + - export PATH="$HOME/.local/bin:$PATH" script: # Optional: start a GitLab MCP server if your setup provides one - /bin/gitlab-mcp-server || true @@ -115,7 +117,7 @@ 2. **Add project credentials for GitLab API operations** : * Use `CI_JOB_TOKEN` by default, or create a Project Access Token with `api` scope * Store as `GITLAB_ACCESS_TOKEN` (masked) if using a PAT - 3. **Add the Claude job to`.gitlab-ci.yml`** (see examples below) + 3. **Add the Claude job to`.gitlab-ci.yml`**: use the Quick setup job for the Claude API, or a provider job from Configuration examples 4. **(Optional) Enable mention-driven triggers** : * Add a project webhook for “Comments (notes)” to your event listener (if you use one) * Have the listener call the pipeline trigger API with variables like `AI_FLOW_INPUT` and `AI_FLOW_CONTEXT` when a comment contains `@claude` @@ -202,18 +204,7 @@ 3. Create an IAM role trusted by the GitLab OIDC provider, restricted to your project and protected refs 4. Attach least-privilege permissions for Amazon Bedrock invoke APIs -**Required values to store in CI/CD variables:** - - * `AWS_ROLE_TO_ASSUME` - * `AWS_REGION` - -Add variables in Settings → CI/CD → Variables: - - # For Amazon Bedrock: - - AWS_ROLE_TO_ASSUME - - AWS_REGION - -Use the Amazon Bedrock job example above to exchange the GitLab job token for temporary AWS credentials at runtime. +Use the Amazon Bedrock job example to exchange the job’s OIDC token for temporary AWS credentials at runtime. ### @@ -227,9 +218,10 @@ * Google Cloud’s Agent Platform API enabled * Workload Identity Federation configured to trust GitLab OIDC 2. A dedicated service account with only the required Google Cloud’s Agent Platform roles - 3. GitLab CI/CD variables for WIF: - * `GCP_WORKLOAD_IDENTITY_PROVIDER` (full resource name) + 3. GitLab CI/CD variables: + * `GCP_WORKLOAD_IDENTITY_PROVIDER` (provider resource name without the `//iam.googleapis.com/` prefix, such as `projects/123456789/locations/global/workloadIdentityPools/my-pool/providers/my-provider`) * `GCP_SERVICE_ACCOUNT` (service account email) + * `GCP_PROJECT_ID` (Google Cloud project ID) ### @@ -244,19 +236,7 @@ 3. Create a dedicated service account with Google Cloud’s Agent Platform roles 4. Grant the WIF principal permission to impersonate the service account -**Required values to store in CI/CD variables:** - - * `GCP_WORKLOAD_IDENTITY_PROVIDER` - * `GCP_SERVICE_ACCOUNT` - -Add variables in Settings → CI/CD → Variables: - - # For Google Cloud's Agent Platform: - - GCP_WORKLOAD_IDENTITY_PROVIDER - - GCP_SERVICE_ACCOUNT - - CLOUD_ML_REGION (for example, us-east5) - -Use the job example above for Google Cloud’s Agent Platform to authenticate without storing keys. +Use the Agent Platform job example to authenticate without storing keys. ## @@ -265,37 +245,6 @@ Configuration examples Below are ready-to-use snippets you can adapt to your pipeline. - -### - -​ - -Basic .gitlab-ci.yml (Claude API) - - stages: - - ai - - claude: - stage: ai - image: node:24-alpine3.21 - rules: - - if: '$CI_PIPELINE_SOURCE == "web"' - - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' - variables: - GIT_STRATEGY: fetch - before_script: - - apk update - - apk add --no-cache git curl bash - - curl -fsSL https://claude.ai/install.sh | bash - script: - - /bin/gitlab-mcp-server || true - - > - claude - -p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}" - --permission-mode acceptEdits - --allowedTools "Bash Read Edit Write mcp__gitlab" - --debug - # Claude Code will use ANTHROPIC_API_KEY from CI/CD variables ### @@ -313,19 +262,28 @@ * `AWS_ROLE_TO_ASSUME`: ARN of the IAM role for Amazon Bedrock access * `AWS_REGION`: Amazon Bedrock region (for example, `us-west-2`) + +GitLab mints the job’s OIDC token from the `id_tokens:` block and exposes it as `GITLAB_OIDC_TOKEN`. Set `aud` to the audience value you configured on the IAM OIDC identity provider in AWS, for example your GitLab instance URL. + + stages: + - ai claude-bedrock: stage: ai image: node:24-alpine3.21 rules: - if: '$CI_PIPELINE_SOURCE == "web"' + id_tokens: + GITLAB_OIDC_TOKEN: + aud: https://gitlab.example.com before_script: - - apk add --no-cache bash curl jq git python3 py3-pip - - pip install --no-cache-dir awscli + - apk add --no-cache bash curl jq git aws-cli - curl -fsSL https://claude.ai/install.sh | bash - # Exchange GitLab OIDC token for AWS credentials - - export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}" - - if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi + # The installer places claude in ~/.local/bin, which isn't on PATH in this image + - export PATH="$HOME/.local/bin:$PATH" + # Exchange the job's OIDC token for AWS credentials + - export AWS_WEB_IDENTITY_TOKEN_FILE="/tmp/oidc_token" + - printf "%s" "$GITLAB_OIDC_TOKEN" > "$AWS_WEB_IDENTITY_TOKEN_FILE" - > aws sts assume-role-with-web-identity --role-arn "$AWS_ROLE_TO_ASSUME" @@ -345,6 +303,7 @@ --debug variables: AWS_REGION: "us-west-2" + CLAUDE_CODE_USE_BEDROCK: "1" Model IDs for Amazon Bedrock include region-specific prefixes (for example, `us.anthropic.claude-sonnet-4-6`). Pass the desired model via your job configuration or prompt if your workflow supports it. @@ -362,31 +321,50 @@ **Required CI/CD variables:** - * `GCP_WORKLOAD_IDENTITY_PROVIDER`: Full provider resource name - * `GCP_SERVICE_ACCOUNT`: Service account email + * `GCP_WORKLOAD_IDENTITY_PROVIDER`: provider resource name without the `//iam.googleapis.com/` prefix, such as `projects/123456789/locations/global/workloadIdentityPools/my-pool/providers/my-provider` + * `GCP_SERVICE_ACCOUNT`: service account email + * `GCP_PROJECT_ID`: Google Cloud project ID * `CLOUD_ML_REGION`: Google Cloud’s Agent Platform region (for example, `us-east5`) + +GitLab mints the job’s OIDC token from the `id_tokens:` block and exposes it as `GITLAB_OIDC_TOKEN`. Set `aud` to the audience value you configured on the Workload Identity Pool provider, for example your GitLab instance URL. The job writes the token to a file, and the credential configuration’s `credential_source` entry tells Google’s auth libraries to read it from there. Setting `GOOGLE_APPLICATION_CREDENTIALS` to the credential configuration file makes it available to Claude Code through [Application Default Credentials](</docs/en/google-vertex-ai#3-configure-gcp-credentials>). + + stages: + - ai claude-vertex: stage: ai image: gcr.io/google.com/cloudsdktool/google-cloud-cli:slim rules: - if: '$CI_PIPELINE_SOURCE == "web"' + id_tokens: + GITLAB_OIDC_TOKEN: + aud: https://gitlab.example.com before_script: - apt-get update && apt-get install -y git && apt-get clean - curl -fsSL https://claude.ai/install.sh | bash - # Authenticate to Google Cloud via WIF (no downloaded keys) - - > - gcloud auth login --cred-file=<(cat <<EOF + # The installer places claude in ~/.local/bin, which isn't on PATH in this image + - export PATH="$HOME/.local/bin:$PATH" + # Write the job's OIDC token where credential_source expects it + - printf "%s" "$GITLAB_OIDC_TOKEN" > /tmp/oidc_token + # Write the WIF credential configuration to a file (no downloaded keys) + - | + cat > /tmp/cred.json <<EOF { "type": "external_account", - "audience": "${GCP_WORKLOAD_IDENTITY_PROVIDER}", + "audience": "//iam.googleapis.com/${GCP_WORKLOAD_IDENTITY_PROVIDER}", "subject_token_type": "urn:ietf:params:oauth:token-type:jwt", - "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${GCP_SERVICE_ACCOUNT}:generateAccessToken", - "token_url": "https://sts.googleapis.com/v1/token" + "token_url": "https://sts.googleapis.com/v1/token", + "credential_source": { + "file": "/tmp/oidc_token" + }, + "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${GCP_SERVICE_ACCOUNT}:generateAccessToken" } EOF - ) - - gcloud config set project "$(gcloud projects list --format='value(projectId)' --filter="name:${CI_PROJECT_NAMESPACE}" | head -n1)" || true + # Expose the credentials to Claude Code via Application Default Credentials + - export GOOGLE_APPLICATION_CREDENTIALS=/tmp/cred.json + # Authenticate the gcloud CLI with the same credential configuration + - gcloud auth login --cred-file=/tmp/cred.json + - gcloud config set project "$GCP_PROJECT_ID" script: - /bin/gitlab-mcp-server || true - > @@ -398,6 +376,8 @@ --debug variables: CLOUD_ML_REGION: "us-east5" + CLAUDE_CODE_USE_VERTEX: "1" + ANTHROPIC_VERTEX_PROJECT_ID: "$GCP_PROJECT_ID" With Workload Identity Federation, you do not need to store service account keys. Use repository-specific trust conditions and least-privilege service accounts. @@ -436,7 +416,6 @@ * Keep `CLAUDE.md` focused and concise * Provide clear issue/MR descriptions to reduce iterations - * Configure sensible job timeouts to avoid runaway runs * Cache npm and package installs in runners where possible ### @@ -456,25 +435,13 @@ * See [Anthropic pricing](<https://platform.claude.com/docs/en/about-claude/pricing>) for details * **Cost optimization tips** : * Use specific `@claude` commands to reduce unnecessary turns - * Set appropriate `max_turns` and job timeout values + * Set appropriate `--max-turns` and job `timeout` values * Limit concurrency to control parallel runs ## ​ -Security and governance - - * Each job runs in an isolated container with restricted network access - * Claude’s changes flow through MRs so reviewers see every diff - * Branch protection and approval rules apply to AI-generated code - * Claude Code uses workspace-scoped permissions to constrain writes - * Costs remain under your control because you bring your own provider credentials - -## - -​ - Troubleshooting ### @@ -484,7 +451,7 @@ Claude not responding to @claude commands * Verify your pipeline is being triggered (manually, MR event, or via a note event listener/webhook) - * Ensure CI/CD variables (`ANTHROPIC_API_KEY` or cloud provider settings) are present and unmasked + * Ensure your `ANTHROPIC_API_KEY` or cloud provider variables are present * Check that the comment contains `@claude` (not `/claude`) and that your mention trigger is configured ### @@ -518,12 +485,12 @@ Common parameters and variables -Claude Code supports these commonly used inputs: - - * `prompt` / `prompt_file`: Provide instructions inline (`-p`) or via a file - * `max_turns`: Limit the number of back-and-forth iterations - * `timeout_minutes`: Limit total execution time - * `ANTHROPIC_API_KEY`: Required for the Claude API (not used for Amazon Bedrock or Google Cloud’s Agent Platform) +Control Claude Code runs in your jobs with these CLI flags, GitLab keywords, and variables: + + * `-p`: provide instructions inline, for example `claude -p "Review this MR"` + * `--max-turns`: limit the number of back-and-forth iterations + * `timeout`: limit total job execution time with GitLab’s job-level `timeout` keyword, for example `timeout: 30m` + * `ANTHROPIC_API_KEY`: required for the Claude API (not used for Amazon Bedrock or Google Cloud’s Agent Platform) * Provider-specific environment: `AWS_REGION`, project/region vars for Google Cloud’s Agent Platform Exact flags and parameters may vary by version of `@anthropic-ai/claude-code`. Run `claude --help` in your job to see supported options. @@ -537,4 +504,4 @@ You can guide Claude in two primary ways: 1. **CLAUDE.md** : Define coding standards, security requirements, and project conventions. Claude reads this during runs and follows your rules. - 2. **Custom prompts** : Pass task-specific instructions via `prompt`/`prompt_file` in the job. Use different prompts for different jobs (for example, review, implement, refactor). + 2. **Custom prompts** : Pass task-specific instructions via `-p` in the job. Use different prompts for different jobs (for example, review, implement, refactor).
modified Keep Claude working toward a goal View current →
--- a/goal.md +++ b/goal.md @@ -1,5 +1,3 @@ -`/goal` requires Claude Code v2.1.139 or later. - The `/goal` command sets a completion condition and Claude keeps working toward it without you prompting each step. After each turn, a small fast model checks whether the condition holds. If not, Claude starts another turn instead of returning control to you. The goal clears automatically once the condition is met. Use a goal for substantial work with a verifiable end state: * Migrating a module to a new API until every call site compiles and tests pass
modified Claude Code on Google Cloud's Agent Platform View current →
--- a/google-vertex-ai.md +++ b/google-vertex-ai.md @@ -130,12 +130,6 @@ # Optional: Override the Agent Platform endpoint URL for custom endpoints or gateways # export ANTHROPIC_VERTEX_BASE_URL=https://aiplatform.googleapis.com - # Optional: Disable prompt caching if needed - # export DISABLE_PROMPT_CACHING=1 - - # Optional: Request 1-hour prompt cache TTL instead of the 5-minute default - # export ENABLE_PROMPT_CACHING_1H=1 - # When CLOUD_ML_REGION=global, override region for models that don't support global endpoints export VERTEX_REGION_CLAUDE_HAIKU_4_5=us-east5 export VERTEX_REGION_CLAUDE_4_6_SONNET=europe-west1 @@ -196,15 +190,13 @@ When Claude Code starts with Google Cloud’s Agent Platform configured, it verifies that the models it intends to use are accessible in your project. If you have pinned a model version that is older than the current Claude Code default, and your project can invoke the newer version, Claude Code prompts you to update the pin. Accepting writes the new model ID to your [user settings file](</docs/en/settings>) and restarts Claude Code. Declining is remembered until the next default version change. If you have not pinned a model and the current default is unavailable in your project, Claude Code falls back for the current session and shows a notice. It tries earlier versions of the default model first and, when the default is an Opus model and no Opus version is available, falls back to the default Sonnet model. The fallback is not persisted. Enable the newer model in [Model Garden](<https://console.cloud.google.com/vertex-ai/model-garden>) or pin a version to make the choice permanent. When you start the session on a specific Sonnet or Opus version, with `--model`, `ANTHROPIC_MODEL`, or the [`model` setting](</docs/en/settings>), that version acts as the session’s pinned default for the matching `sonnet` or `opus` alias. Claude Code skips the availability check for the built-in default your model replaces and starts on the model you configured, with no fallback notice. Model aliases such as `opus` don’t act as pins, and neither does a model ID Claude Code doesn’t recognize. -Before v2.1.211, Claude Code checked the default model’s availability even when a session model was explicitly configured, and could show a fallback notice for a default the session didn’t use. - ## ​ IAM configuration -Assign the required IAM permissions: The `roles/aiplatform.user` role includes the required permissions: +Assign the `roles/aiplatform.user` role, which includes the required permissions: * `aiplatform.endpoints.predict` \- Required for model invocation and token counting
modified Intercept and control agent behavior with hooks View current →
--- a/hooks.md +++ b/hooks.md @@ -163,7 +163,7 @@ `PreCompact`| Yes| Yes| Conversation compaction request| Archive full transcript before summarizing `PostCompact`| No| Yes| Conversation compaction completes| Log the generated summary `PermissionRequest`| Yes| Yes| A tool call needs a permission decision| Custom permission handling -`PermissionDenied`| No| Yes| The auto mode classifier denies a tool call| Log classifier denials or tell the model it may retry +`PermissionDenied`| No| Yes| Auto mode denies a tool call, including denials without a classifier verdict| Log denials, or tell the model it may retry; Claude Code ignores `retry: true` for no-verdict denials. See [PermissionDenied](</docs/en/hooks#permissiondenied>) `SessionStart`| No| Yes| Session initialization| Initialize logging and telemetry `SessionEnd`| No| Yes| Session termination| Clean up temporary resources `Notification`| Yes| Yes| Agent status messages| Send agent status updates to Slack or PagerDuty @@ -224,15 +224,15 @@ Matchers -Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. See the [Claude Code hooks reference](</docs/en/hooks#matcher-patterns>) for the full list of matcher values for each event type. SDK matchers follow the same rules as [matchers in settings files](</docs/en/hooks#matcher-patterns>). A matcher containing only letters, digits, `_`, `-`, spaces, `,`, and `|` is compared as an exact string, with alternatives separated by `|` or `,` and optional surrounding whitespace, so `Write|Edit` and `Write, Edit` each match exactly those two tools and `code-reviewer` matches only that agent type. A matcher of `*`, an empty string, or omitting the matcher entirely matches every occurrence of the event. A matcher containing any other character is evaluated as an unanchored regular expression, so `^mcp__` matches every MCP tool and `Edit.*` matches both `Edit` and `NotebookEdit`. Wrap a regular expression in `^` and `$` when you need a whole-string match. A matcher like `mcp__memory` or `mcp__brave-search` contains only exact-match characters, so it is compared as an exact string and matches no tool; use `mcp__memory__.*` to match every tool from that server. Hyphens in the exact-match set require a Claude Code runtime of v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression and must be anchored as `^code-reviewer$` to match exactly. `StopFailure` and `FileChanged` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives, so write `rate_limit|overloaded`, not `rate_limit, overloaded`. `FileChanged` additionally uses its matcher to build the watch list of literal filenames; see [FileChanged in the hooks reference](</docs/en/hooks#filechanged>). +Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. SDK matchers follow the same rules as [matchers in settings files](</docs/en/hooks#matcher-patterns>). That section documents the exact-string and regular-expression evaluation paths, their version requirements, and the matcher values for each event type. Option| Type| Default| Description ---|---|---|--- -`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the comparison rules above. For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list). MCP tools use the pattern `mcp__<server>__<action>`. +`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the [rules for matchers in settings files](</docs/en/hooks#matcher-patterns>). For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list). MCP tools use the pattern `mcp__<server>__<action>`. `hooks`| `HookCallback[]`| -| Required. Array of callback functions to execute when the pattern matches -`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout: 10 minutes for most events, 30 seconds for `UserPromptSubmit`. Claude Code uses shorter limits for a few events, such as 10 seconds for `MessageDisplay` and a 1.5-second default [budget](</docs/en/hooks#sessionend-input>) for `SessionEnd`. Your SDK callbacks follow the `command` hook defaults - -Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event. For tool-based hooks, matchers only filter by tool name, not by file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your callback. +`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout. Your SDK callbacks follow the `command` hook defaults + +Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event. **Discovering tool names:** See [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list of built-in tool names, or add a hook without a matcher to log all tool calls your session makes.**MCP tool naming:** MCP tools always start with `mcp__` followed by the server name and action: `mcp__<server>__<action>`. For example, if you configure a server named `playwright`, its tools are named `mcp__playwright__browser_screenshot`, `mcp__playwright__browser_click`, and so on. The server name comes from the key you use in the `mcpServers` configuration. @@ -264,7 +264,7 @@ Your callback returns an object with two categories of fields: - * **Top-level fields** work the same on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook. + * **Top-level fields** are accepted on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook. Some events discard them or deliver them elsewhere. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says where they land. * **`hookSpecificOutput`** controls the current operation. The fields inside depend on the hook event type. For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. Returning `"defer"` ends the query so you can [resume it later](</docs/en/hooks#defer-a-tool-call-for-later>). For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated. Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references. @@ -815,7 +815,7 @@ Hook timeout -Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>). When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback’s output and the session continues rather than hanging. What happens next depends on the event: +Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback’s output and the session continues rather than hanging. What happens next depends on the event: * `PreToolUse`: Claude Code doesn’t run the tool call, Claude receives a tool result stating the hook didn’t respond before its timeout, and the turn continues. If another `PreToolUse` hook returned an explicit deny, Claude receives that denial instead of the timeout error. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input. * `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues. @@ -902,7 +902,7 @@ systemMessage not appearing in output -The `systemMessage` field shows a message to the user, not the model. By default the SDK surfaces hook output in the message stream only for `SessionStart` and `Setup` hooks, so a message from any other hook event doesn’t appear unless you set `includeHookEvents` (`include_hook_events` in Python). To pass context to the model instead, return [`additionalContext`](</docs/en/hooks#add-context-for-claude>). If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel. +The `systemMessage` field shows a message to the user, not the model. On Claude Code v2.1.227 or later, a hook’s `systemMessage` can surface in the message stream as an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>). Whether it does depends on the event. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says how output surfaces. To pass context to the model instead, return [`additionalContext`](</docs/en/hooks#add-context-for-claude>). Before v2.1.227, the SDK surfaced hook output in the message stream only for `SessionStart` and `Setup` hooks. For any other event, the output appeared only in the lifecycle events that [`includeHookEvents`](</docs/en/agent-sdk/typescript#options>) (`include_hook_events` in Python) adds. That option’s entry covers which lifecycle events each hook event produces. If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel. ##
modified Automate actions with hooks View current →
--- a/hooks-guide.md +++ b/hooks-guide.md @@ -436,7 +436,7 @@ `UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion `PreToolUse`| Before a tool call executes. Can block it `PermissionRequest`| When a tool call needs a permission decision -`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call +`PermissionDenied`| When auto mode denies a tool call, including denials without a classifier verdict. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry the denied tool call. Claude Code ignores `retry` when the classifier produced no verdict `PostToolUse`| After a tool call succeeds `PostToolUseFailure`| After a tool call fails `PostToolBatch`| After a full batch of parallel tool calls resolves, before the next model call @@ -447,7 +447,7 @@ `TaskCreated`| When a task is being created via `TaskCreate` `TaskCompleted`| When a task is being marked as completed `Stop`| When Claude finishes responding -`StopFailure`| When the turn ends due to an API error. Output and exit code are ignored +`StopFailure`| When the turn ends due to an API error `TeammateIdle`| When an [agent team](</docs/en/agent-teams>) teammate is about to go idle `InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session `ConfigChange`| When a configuration file changes during a session @@ -554,11 +554,12 @@ The exit code determines what happens next: - * **Exit 0** : the hook reports no objection and the action proceeds normally. For a `PreToolUse` hook this doesn’t approve the tool call: the normal [permission flow](</docs/en/permissions>) still applies. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude’s context. - * **Exit 2** : Claude Code blocks the action. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events can’t be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](</docs/en/hooks#exit-code-2-behavior-per-event>) for the full list. - * **Any other exit code** : the action proceeds - * The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:` - * To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session + * **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, anything you write to stdout is added 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. + * **Any other exit code** : for most events, the outcome depends on what your hook printed to stdout: + * JSON 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. + * JSON that parses but fails schema validation: a non-blocking error; the notice carries the validation message. + * No JSON on stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session. #### @@ -568,7 +569,7 @@ Exit codes only let you block or stay silent. For more control, exit 0 and print a JSON object to stdout instead. -Use exit 2 to block with a stderr message, or exit 0 with JSON for structured control. Don’t mix them: Claude Code ignores JSON when you exit 2. +Use exit 2 to block with a stderr message, or exit 0 with JSON for structured control. Choose one approach per hook. For what happens when you mix them, see [Exit code output](</docs/en/hooks#exit-code-output>). For example, a `PreToolUse` hook can deny a tool call and tell Claude why, or escalate it to the user for approval: @@ -918,6 +919,7 @@ * If you see “command not found”, use absolute paths or `${CLAUDE_PROJECT_DIR}` to reference scripts. To avoid shell quoting entirely, add `"args": []` to switch to [exec form](</docs/en/hooks#exec-form-and-shell-form>), which spawns the script directly without a shell * If you see “jq: command not found”, install `jq` or use Python/Node.js for JSON parsing + * If the notice shows a JSON validation message, your hook’s stdout parsed as JSON but failed schema validation. This happens even on exit 0. The reference’s [Exit code output](</docs/en/hooks#exit-code-0>) section covers the exit-code and JSON combinations * If the script isn’t running at all, make it executable: `chmod +x ./my-hook.sh` ### @@ -953,14 +955,14 @@ ​ -JSON validation failed - -Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON: +Hook JSON has no effect + +Your hook prints valid JSON, but the decision doesn’t take effect and no error appears in the transcript. When Claude Code runs a shell-form command hook, one without `args`, it spawns `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed by default. This shell is non-interactive, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile. If that profile contains unconditional `echo` statements, the output gets prepended to your hook’s JSON: Shell ready on arm64 {"decision": "block", "reason": "Not allowed"} -Claude Code tries to parse this as JSON and fails. To fix this, wrap echo statements in your shell profile so they only run in interactive shells: +The combined output no longer starts with `{`, so Claude Code treats all of stdout as plain text and ignores the JSON. On exit 0 nothing is reported in the transcript; the parse attempt is recorded only in the [debug log](</docs/en/hooks#debug-hooks>). To fix this, wrap echo statements in your shell profile so they only run in interactive shells: # In ~/.zshrc or ~/.bashrc if [[ $- == *i* ]]; then @@ -977,12 +979,12 @@ Press `Ctrl+O` to open the transcript view to check the outcome of a hook run: - * After a successful run, where the hook exited 0, you see nothing + * **Successful run** : you see nothing, unless the hook’s JSON surfaces something, such as `systemMessage` or Stop hook feedback. * To confirm a hook ran, check for its effect, like a reformatted file, or turn on debug logging as described below and trigger the hook again - * After a blocking error, where the hook exited 2 and Claude Code stopped the action, you see the hook’s stderr - * After a non-blocking error, where the hook exited with any other code and the action proceeded, you see a `<hook name> hook error` notice followed by the first line of stderr, prefixed with `Failed with non-blocking status code:` - -For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path. + * **Blocking error** : on most events you see the hook’s feedback. When the hook’s JSON made a blocking decision, the feedback is the reason from that decision; otherwise it is the hook’s stderr. On a few events, such as `ConfigChange` and `Elicitation`, a block surfaces no message. + * **Non-blocking error** : the action proceeded, and you see a `<hook name> hook error` notice with a short explanation, such as the first line of stderr prefixed with `Failed with non-blocking status code:` or a JSON validation message. + +Which exit-code and JSON combinations produce each outcome, including the per-event exceptions, is defined in the reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section. For full execution details including which hooks matched, their exit codes, stdout, and stderr, read the debug log. Start Claude Code with `claude --debug-file /tmp/claude.log` to write to a known path, then `tail -f /tmp/claude.log` in another terminal. If you started without that flag, run `/debug` mid-session to enable logging and find the log path. ##
modified Hosting the Agent SDK View current →
--- a/hosting.md +++ b/hosting.md @@ -214,7 +214,7 @@ Default local disk is lost on restart, scale-down, or a move to a different node. For any session a user expects to resume, mirror the transcript to durable storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). See [Reference implementations](</docs/en/agent-sdk/session-storage#reference-implementations>) for S3, Redis, and Postgres adapters and a conformance suite for your own. Three things to know about how `SessionStore` behaves: * **Transcripts only** : `SessionStore` mirrors transcripts, not `CLAUDE.md` memory files or other working-directory artifacts. Mount a shared volume or sync those separately. - * **Mirror, not replacement** : the subprocess writes to local disk first, and the store receives a copy of each batch. Local writes remain authoritative. + * **Mirror, not replacement** : the subprocess writes to local disk first, and the SDK forwards a copy of each batch to the store. A fresh session’s local transcript outlives the run; a run resumed from the store deletes its local copy at the end, so the store holds the only durable copy. See [Dual-write architecture](</docs/en/agent-sdk/session-storage#dual-write-architecture>). * **`mirror_error` messages**: when the SDK can’t deliver a batch to the store, it drops the batch, emits a `{ type: "system", subtype: "mirror_error" }` message, and continues the query. Alert on these if store durability matters. See [Mirror writes are best-effort](</docs/en/agent-sdk/session-storage#mirror-writes-are-best-effort>) for the retry and timeout behavior. ###
modified Interactive mode View current →
Show diff (157 lines)
--- a/interactive-mode.md +++ b/interactive-mode.md @@ -4,13 +4,7 @@ Keyboard shortcuts -Keyboard shortcuts may vary by platform and terminal. In [fullscreen rendering](</docs/en/fullscreen>), press `?` in the transcript viewer to see available shortcuts there.**macOS users** : Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+P`) require configuring Option as Meta in your terminal: - - * **iTerm2** : Settings → Profiles → Keys → General → set Left/Right Option key to “Esc+” - * **Apple Terminal** : Settings → Profiles → Keyboard → check “Use Option as Meta Key” - * **VS Code** : set `"terminal.integrated.macOptionIsMeta": true` in VS Code settings - -See [Terminal configuration](</docs/en/terminal-config>) for details. +Keyboard shortcuts may vary by platform and terminal. In [fullscreen rendering](</docs/en/fullscreen>), press `?` in the transcript viewer to see available shortcuts there.**macOS users** : Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+P`) require configuring Option as Meta in your terminal. See [Enable Option key shortcuts on macOS](</docs/en/terminal-config#enable-option-key-shortcuts-on-macos>) for the setting in each terminal. ### @@ -33,9 +27,9 @@ `Ctrl+S`| Stash or restore prompt| With text in the input, stashes it and clears the prompt. Pressed again on an empty prompt, restores the stashed text, cursor position, and pasted content `Ctrl+Z`| Suspend Claude Code| Unix only. Suspends the process to your shell; run `fg` to resume `Left/Right arrows`| Cycle through dialog tabs| Navigate between tabs in permission dialogs and menus -`Up/Down arrows` or `Ctrl+P`/`Ctrl+N`| Move cursor or navigate command history| When the input spans more than one visual row, whether wrapped or multiline, first moves the cursor within the prompt. Once the cursor is on the first or last visual row, pressing again navigates command history. As of v2.1.169, wrapped single-line input behaves the same as multiline -`Esc`| Interrupt Claude, or close a dialog| Stop the current response or tool call mid-turn so you can redirect. Claude keeps the work done so far. When a dialog such as a permission prompt is open, `Esc` closes the dialog rather than interrupting Claude. Before v2.1.202, `Esc` on some dialogs interrupted Claude and left the dialog open -`Esc` \+ `Esc`| Clear input draft, or rewind| When the prompt input contains text, double `Esc` clears it and saves the draft to history so `Up` recalls it. When the input is empty, double `Esc` opens the [rewind menu](</docs/en/checkpointing>) to restore or summarize code and conversation from a previous point. Before v2.1.216, double `Esc` at an empty prompt could stop opening the menu for the rest of a long-running session that used background tasks +`Up/Down arrows` or `Ctrl+P`/`Ctrl+N`| Move cursor or navigate command history| When the input spans more than one visual row, whether wrapped or multiline, first moves the cursor within the prompt. Once the cursor is on the first or last visual row, pressing again navigates command history +`Esc`| Interrupt Claude, or close a dialog| Stop the current response or tool call mid-turn so you can redirect. Claude keeps the work done so far. When a dialog such as a permission prompt is open, `Esc` closes the dialog rather than interrupting Claude +`Esc` \+ `Esc`| Clear input draft, or rewind| When the prompt input contains text, double `Esc` clears it and saves the draft to history so `Up` recalls it. When the input is empty, double `Esc` opens the [rewind menu](</docs/en/checkpointing>) to restore or summarize code and conversation from a previous point `Shift+Tab`, or `Alt+M` on Windows when the Node or Bun runtime doesn’t enable VT input mode| Cycle permission modes| Cycle through `default` (labeled Manual in the mode indicator), `acceptEdits`, `plan`, and any modes you have enabled, such as `auto` or `bypassPermissions`. See [permission modes](</docs/en/permission-modes>). `Option+P` (macOS) or `Alt+P` (Windows/Linux)| Switch model| Switch models without clearing your prompt `Option+T` (macOS) or `Alt+T` (Windows/Linux)| Toggle extended thinking| Enable or disable extended thinking mode. Has no effect on Fable 5, which always uses extended thinking. Works on macOS without configuring Option as Meta @@ -80,11 +74,9 @@ ---|---|--- Quick escape| `\` \+ `Enter`| Works in all terminals Option key| `Option+Enter`| After enabling [Option as Meta](</docs/en/terminal-config#enable-option-key-shortcuts-on-macos>) on macOS -Shift+Enter| `Shift+Enter`| Native in iTerm2, WezTerm, Ghostty, Kitty, Warp, Apple Terminal, Windows Terminal +Shift+Enter| `Shift+Enter`| Native in iTerm2, WezTerm, Ghostty, Kitty, Warp, Apple Terminal, Windows Terminal. For other terminals, see [Enter multiline prompts](</docs/en/terminal-config#enter-multiline-prompts>) Control sequence| `Ctrl+J`| Works in any terminal without configuration Paste mode| Paste directly| For code blocks, logs - -Shift+Enter works without configuration in iTerm2, WezTerm, Ghostty, Kitty, Warp, Apple Terminal, and Windows Terminal. For VS Code, Cursor, Devin Desktop, Alacritty, and Zed, run `/terminal-setup` to install the binding. ### @@ -98,7 +90,7 @@ `!` at start| Shell mode| Run a command directly, add its output to the session, and have Claude respond to it `@`| File path mention| Trigger file path autocomplete `:`| Emoji shortcode| Type a full `:name:` to insert the emoji, or two or more characters for suggestions. See Emoji shortcodes. Requires Claude Code v2.1.217 or later -`?` on empty input| Toggle the shortcut help panel| Typing `?` when the input already contains text inserts the character. Before v2.1.211, an edit that left a lone `?` in the input, such as backspacing from `?x`, also toggled the panel and discarded the edit +`?` on empty input| Toggle the shortcut help panel| Typing `?` when the input already contains text inserts the character ### @@ -106,7 +98,7 @@ Transcript viewer -When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. Run `/tui` with no argument to check which renderer is active. In [fullscreen rendering](</docs/en/fullscreen>), press `?` to show the full shortcut reference panel inside the viewer. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](</docs/en/keybindings>). +When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. Run `/tui` with no argument to check which renderer is active. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](</docs/en/keybindings>). Shortcut| Description ---|--- @@ -200,7 +192,7 @@ `T{char}`| Jump to just after previous occurrence of character `;`| Repeat last f/F/t/T motion `,`| Repeat last f/F/t/T motion in reverse -`/`| Open reverse history search, same as `Ctrl+R`. As of v2.1.191, the empty search prompt shows a hint: press `Esc` then `i` then `/` to open the command menu instead +`/`| Open reverse history search, same as `Ctrl+R`. The empty search prompt shows a hint: press `Esc` then `i` then `/` to open the command menu instead In vim NORMAL mode, if the cursor is at the beginning or end of input and can’t move further, `j`/`k` and `↑`/`↓` navigate command history instead. `←` on an empty prompt opens [agent view](</docs/en/agent-view>) from NORMAL mode as well as INSERT; before v2.1.219, `←` on an empty prompt did nothing in NORMAL mode. @@ -229,7 +221,7 @@ `<<`| Dedent line `J`| Join lines `u`| Undo -`.`| Repeat last change. Before v2.1.216, repeating a change operator such as `cw` or `cc` replayed only the inserted text without the deletion, and `.` after `p`/`P` repeated the previous change instead of the paste +`.`| Repeat last change ### @@ -284,7 +276,6 @@ * Input history is stored per working directory * Running `/clear` starts a new session: recall then lists the new session’s prompts first, with earlier sessions’ prompts after them. The previous session’s conversation is preserved and can be resumed. * Submitting the same prompt twice in a row records one history entry, so pressing Up steps to the previous distinct prompt - * Use Up/Down arrows to navigate (see keyboard shortcuts above) * When you recall a prompt that included pasted text, Claude Code sends the full pasted content again when you resubmit. If the content has since been [cleaned up](</docs/en/claude-directory#cleaned-up-automatically>), Claude Code doesn’t send the literal `[Pasted text #N]` string; see [Paste large content](</docs/en/terminal-config#paste-large-content>) for what happens to the prompt * History expansion with `!` is disabled by default @@ -307,7 +298,7 @@ * Press `Ctrl+C` to cancel and restore your original input * Press `Backspace` on empty search to cancel -The inline search scans your full prompt history, newest first, with duplicates collapsed to the newest occurrence. The fullscreen dialog lists the 100 most recent unique prompts in the selected scope. Matching prompts display with the search term highlighted, so you can find and reuse previous inputs. Accepting a match or canceling the search takes effect immediately, even while Claude Code is still loading the history. Before v2.1.202, accepting or canceling during that load could report an internal error. +The inline search scans your full prompt history, newest first, with duplicates collapsed to the newest occurrence. The fullscreen dialog searches your whole prompt history in the selected scope, newest first, with duplicates collapsed to the newest occurrence: the most recent prompts appear immediately, and matches from older prompts fill in as Claude Code loads the rest. Matching prompts display with the search term highlighted, so you can find and reuse previous inputs. Accepting a match or canceling the search takes effect immediately, even while Claude Code is still loading the history. ## @@ -334,7 +325,7 @@ * Background tasks have unique IDs for tracking and output retrieval * Background tasks are automatically cleaned up when Claude Code exits. If you background the session instead of exiting it, Claude Code hands them to the background session, where they keep running. See [background a running session](</docs/en/agent-view#from-inside-a-session>) * Background tasks are automatically terminated if output exceeds 5GB, with a note in stderr explaining why - * On macOS and Linux, Claude Code terminates running background tasks when the operating system signals memory pressure, provided the session has been idle for at least 30 minutes and no turn or subagent is running. Set [`CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP`](</docs/en/env-vars>) to `1` to turn this off. Requires Claude Code v2.1.193 or later. Background commands owned by a [subagent](</docs/en/sub-agents>) are instead terminated after 60 minutes, configurable in milliseconds with [`CLAUDE_SUBAGENT_BG_SHELL_MAX_MS`](</docs/en/env-vars>). Before v2.1.218, neither limit covered commands moved to the background with `Ctrl+B` + * On macOS and Linux, Claude Code terminates running background tasks when the operating system signals memory pressure, provided the session has been idle for at least 30 minutes and no turn or subagent is running. Set [`CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP`](</docs/en/env-vars>) to `1` to turn this off. Requires Claude Code v2.1.193 or later. Background commands owned by a [subagent](</docs/en/sub-agents>) are instead terminated after 60 minutes, configurable in milliseconds with [`CLAUDE_SUBAGENT_BG_SHELL_MAX_MS`](</docs/en/env-vars>). A command owned by a subagent running in the foreground also ends when that subagent gives its final response; see [Background commands](</docs/en/tools-reference#background-commands>) in the tools reference. Before v2.1.218, neither the memory-pressure reap nor the 60-minute limit covered commands moved to the background with `Ctrl+B` To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](</docs/en/env-vars>) for details. **Common backgrounded commands:** @@ -367,7 +358,7 @@ * Exit with `Escape`, `Backspace`, or `Ctrl+U` on an empty prompt * Pasting text that starts with `!` into an empty prompt enters shell mode automatically, matching typed `!` behavior -As of v2.1.186, Claude responds to the command output automatically once it lands in the transcript, so you can run `! npm test` and get an explanation of the failures without a second prompt. The response costs the same as sending a normal prompt. To restore the earlier behavior where the output is added to context without a response, set [`respondToBashCommands`](</docs/en/settings#available-settings>) to `false` in `settings.json`. Before v2.1.186, shell mode always added output to context without a response. This is useful for quick shell operations while maintaining conversation context. +Claude responds to the command output automatically once it lands in the transcript, so you can run `! npm test` and get an explanation of the failures without a second prompt. The response costs the same as sending a normal prompt. To restore the earlier behavior where the output is added to context without a response, set [`respondToBashCommands`](</docs/en/settings#available-settings>) to `false` in `settings.json`. Before v2.1.186, shell mode always added output to context without a response. ## @@ -409,24 +400,24 @@ Side questions with /btw -Use `/btw` to ask a quick question about your current work without adding to the conversation history. This is useful when you want a fast answer but don’t want to clutter the main context or derail Claude from a long-running task. +Use `/btw` to ask a question about your current work without adding to the conversation history. /btw what was the name of that config file again? -Side questions have full visibility into the current conversation, so you can ask about code Claude has already read, decisions it made earlier, or anything else from the session. The question and answer are ephemeral: they appear in a dismissible overlay and never enter the conversation history. - - * **Available while Claude is working** : you can run `/btw` even while Claude is processing a response. The side question runs independently and doesn’t interrupt the main turn. +Claude answers a side question from what’s already in the conversation: your messages, its replies, and the tool results it has gathered. You can ask about code Claude has already read, decisions it made earlier, or anything else from the session. A later side question also sees your earlier side questions: Claude Code replays the newest 20 exchanges with each ask, until you clear them. The question and answer never enter the conversation history. In the terminal, they appear in a dismissible overlay. The terminal keeps the thread in memory: press `x` to clear the earlier exchanges, and it’s gone when you exit Claude Code. In the [VS Code extension](</docs/en/vs-code#use-the-prompt-box>)’s chat panel, `/btw` opens a panel rather than the overlay this section describes, and you ask follow-up questions right in the panel. The panel’s thread survives window reloads, on the retention schedule that page describes. You need the extension at v2.1.227 or later. Earlier extension versions don’t offer `/btw`. + + * **Available while Claude is working** : you can run `/btw` even while Claude is processing a response. The side question runs independently and doesn’t interrupt the main turn. It sees everything in the conversation so far, except the reply Claude is still writing. * **No tool access** : side questions answer only from what is already in context. Claude can’t read files, run commands, or search when answering a side question. - * **Single response** : there are no follow-up turns in the overlay. To continue the thread, fork it into its own session with `f`. - * **Low cost** : the side question reuses the parent conversation’s prompt cache, so the additional cost is minimal. - -Earlier side questions from the same session appear as a dimmed list above the current answer. They stay out of the conversation history but remain visible in the overlay until you clear them. To return to the overlay after dismissing it, run `/btw` with no question. The overlay reopens on your most recent exchange. Press `Left` to step back through earlier answers. Before v2.1.212, `/btw` without a question printed a usage message instead. Once the answer appears, the overlay accepts these keys. + * **Single response** : there are no follow-up turns in the overlay. To continue the thread, ask another `/btw` question. To continue with full tool access, fork this question and answer into their own session with `f`. + * **Low cost** : while the conversation’s [prompt cache](</docs/en/prompt-caching>) is warm, a side question costs little beyond the answer itself. + +Your five newest earlier side questions appear as a dimmed list above the current answer, with a count of any older ones. They stay out of the conversation history. To return to the overlay after dismissing it, run `/btw` with no question. The overlay reopens on your most recent exchange. Press `Left` to step back through earlier answers. Before v2.1.212, `/btw` without a question printed a usage message instead. Once the answer appears, the overlay accepts these keys. Key| Action ---|--- `Space`, `Enter`, `Escape`| Dismiss the answer and return to the prompt `Up` / `Down`| Scroll the answer -`Left` / `Right`| Step between this answer and your earlier `/btw` answers from the session. `Left` moves to older answers and `Right` returns toward the current one. Requires Claude Code v2.1.187 or later +`Left` / `Right`| Step between this answer and your earlier `/btw` answers. `Left` moves to older answers and `Right` returns toward the current one. Requires Claude Code v2.1.187 or later `c`| Copy the answer to your clipboard as raw Markdown. Use this instead of mouse selection, which captures the hard-wrapped terminal rendering rather than the source text `f`| Fork into a new session. The fork inherits the parent conversation plus this question and answer as real transcript turns, so you can continue with full tool access. The original session is preserved under [`/resume`](</docs/en/commands>). Available in local sessions only `x`| Clear the list of earlier `/btw` exchanges shown above the current answer @@ -467,7 +458,7 @@ * Red: changes requested * Gray: draft -The badge disappears once the pull request merges or closes. `Cmd+click` (macOS) or `Ctrl+click` (Windows/Linux) the link to open the pull request in your browser. The status refreshes every 60 seconds, and immediately after a `gh pr` or `git push` command runs in the session. Claude Code renders the badge as a hyperlink even when it can’t detect hyperlink support in your terminal, which commonly happens over SSH or in tmux. Set [`FORCE_HYPERLINK=0`](</docs/en/env-vars>) to render the badge as plain text. Before v2.1.217, the badge was a hyperlink only when detection succeeded. +The badge disappears once the pull request merges or closes. `Cmd+click` (macOS) or `Ctrl+click` (Windows/Linux) the link to open the pull request in your browser. The status refreshes every 60 seconds, and immediately after a `gh pr` or `git push` command runs in the session. Claude Code renders the badge as a hyperlink even when it can’t detect hyperlink support in your terminal, which commonly happens over SSH or in tmux. Set [`FORCE_HYPERLINK=0`](</docs/en/env-vars>) to render the badge as plain text. PR status requires the `gh` CLI to be installed and authenticated (`gh auth login`).
modified Connect Claude Code to an LLM gateway View current →
--- a/llm-gateway-connect.md +++ b/llm-gateway-connect.md @@ -274,7 +274,7 @@ Slack, web, and Remote Control -[Claude Code in Slack](</docs/en/slack>) and [Claude Code on the web](</docs/en/claude-code-on-the-web>) are Anthropic-hosted products that always use Anthropic’s API; they aren’t part of a gateway deployment. Gateway variables set in a cloud session’s environment configuration are not applied. If your traffic must stay on the gateway, don’t enable these surfaces for those users. [Remote Control](</docs/en/remote-control>) and [voice dictation](</docs/en/voice-dictation>) both rely on a claude.ai identity: Remote Control to pair a live session with your account, and voice dictation to reach the claude.ai transcription endpoint. They are unavailable while `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or an `apiKeyHelper` is active. As of v2.1.196, Remote Control is also disabled while `ANTHROPIC_BASE_URL` points at a non-Anthropic host, so signing in with claude.ai isn’t enough on its own. To restore either feature, log in with claude.ai and unset the gateway variables that feature checks. The Remote Control section of `claude doctor` names the credential variable to unset. +[Claude Code in Slack](</docs/en/slack>) and [Claude Code on the web](</docs/en/claude-code-on-the-web>) are Anthropic-hosted products that always use Anthropic’s API; they aren’t part of a gateway deployment. Gateway variables set in a cloud session’s environment configuration are not applied. If your traffic must stay on the gateway, don’t enable these surfaces for those users. [Remote Control](</docs/en/remote-control>) and [voice dictation](</docs/en/voice-dictation>) both rely on a claude.ai identity: Remote Control to pair a live session with your account, and voice dictation to reach the claude.ai transcription endpoint. They are unavailable while `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or an `apiKeyHelper` is active. Remote Control is also disabled while `ANTHROPIC_BASE_URL` points at a non-Anthropic host, so signing in with claude.ai isn’t enough on its own. To restore either feature, log in with claude.ai and unset the gateway variables that feature checks. The Remote Control section of `claude doctor` names the credential variable to unset. * Voice dictation: unset the gateway credential * Remote Control: unset the gateway credential and `ANTHROPIC_BASE_URL` @@ -325,7 +325,7 @@ Rotate credentials with apiKeyHelper -An `apiKeyHelper` is a command Claude Code runs to fetch your gateway credential, instead of reading it from a static environment variable. Use a helper when the credential expires on a schedule, comes from a vault or SSO command, or your administrator told you to configure one. If your credential is a fixed string you set once, the credential variable is all you need and you can skip this section. The helper is any shell command that prints the current credential to stdout. Claude Code runs it through your system shell, so on Windows it can be an executable or a PowerShell invocation. Write the script, make it executable, and reference it from `apiKeyHelper` in your [settings file](</docs/en/settings>): +An `apiKeyHelper` is a command Claude Code runs to fetch your gateway credential, instead of reading it from a static environment variable. Use a helper when the credential expires on a schedule, comes from a vault or SSO command, or your administrator told you to configure one. If your credential is a fixed string you set once, the credential variable is all you need and you can skip this section. The helper is any shell command that prints the current credential to stdout. Claude Code runs it through your system shell, so on Windows it can be an executable or a PowerShell invocation. Make the command print nothing but the credential. On Claude Code v2.1.227 or later, a banner or a log line printed alongside the key makes the [helper fail](</docs/en/errors#your-apikeyhelper-script-is-failing>). Write the script, make it executable, and reference it from `apiKeyHelper` in your [settings file](</docs/en/settings>): * Bash or Zsh @@ -384,7 +384,7 @@ Route to a cloud provider through a gateway -These configurations point Claude Code at a gateway through a provider-specific base URL variable in place of `ANTHROPIC_BASE_URL`. Amazon Bedrock and Google Cloud’s Agent Platform gateways accept those providers’ native request formats; Microsoft Foundry and Claude Platform on AWS gateways accept the Anthropic Messages format and differ only in which base URL variable reaches them. Use one only if your gateway team specifically named Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or the Claude Platform on AWS. If the verification request above returned JSON, you can skip this section. Set the block for the provider your gateway team named. The skip-auth variables tell Claude Code not to sign requests with provider credentials, since the gateway holds those. If the gateway needs its own token, add `ANTHROPIC_AUTH_TOKEN` after the block, except for Microsoft Foundry, which uses `ANTHROPIC_FOUNDRY_API_KEY` as shown. A Microsoft Foundry gateway that expects a bearer token can use [`ANTHROPIC_FOUNDRY_AUTH_TOKEN`](</docs/en/env-vars>) instead; it takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` when both are set. `ANTHROPIC_FOUNDRY_AUTH_TOKEN` requires Claude Code v2.1.203 or later. +These configurations point Claude Code at a gateway through a provider-specific base URL variable in place of `ANTHROPIC_BASE_URL`. Amazon Bedrock and Google Cloud’s Agent Platform gateways accept those providers’ native request formats; Microsoft Foundry and Claude Platform on AWS gateways accept the Anthropic Messages format and differ only in which base URL variable reaches them. Use one only if your gateway team specifically named Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or the Claude Platform on AWS. If the verification request above returned JSON, you can skip this section. Set the block for the provider your gateway team named. The skip-auth variables tell Claude Code not to sign requests with provider credentials, since the gateway holds those. If the gateway needs its own token, add `ANTHROPIC_AUTH_TOKEN` after the block, except for Microsoft Foundry, which uses `ANTHROPIC_FOUNDRY_API_KEY` as shown. #### @@ -468,6 +468,20 @@ $env:CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH = "1" $env:CLAUDE_CODE_USE_ANTHROPIC_AWS = "1" +#### + +​ + +Confirm the provider route + +Start `claude` from the shell where you set the block and run `/status`. With the Amazon Bedrock block, the **Status** tab shows rows like these: + + API provider: Amazon Bedrock + Bedrock base URL: https://llm-gateway.example.com/bedrock + AWS auth skipped + +The other blocks produce the same rows under their provider’s names, for example `Vertex base URL` and `GCP auth skipped` for Google Cloud’s Agent Platform; the Microsoft Foundry block shows an auth skipped row only if you set `CLAUDE_CODE_SKIP_FOUNDRY_AUTH`. If you also route through a corporate proxy, a `Proxy` row shows the proxy URL. If the base URL row is missing, the variable didn’t reach the session. + ## ​ @@ -480,8 +494,8 @@ ---|---|--- A startup warning naming two credential sources and ending in `auth may not work as expected`. Older versions show `Auth conflict: Both a token (SOURCE) and an API key (SOURCE) are set` instead.| A gateway credential and a saved login are both active; the variable is used for requests, but the stale login can cause unexpected auth behavior| Unset the variable to use the saved login, or run `/logout` to use the gateway credential `401` errors naming an invalid or unrecognized token| The credential isn’t one the gateway issued, or it’s in a header the gateway doesn’t read| Confirm the variable matches your credential kind in the credential table, and regenerate the key at the gateway if it was revoked -`Your apiKeyHelper script is failing`| The command in the [`apiKeyHelper`](</docs/en/settings#available-settings>) setting exited with an error, timed out, or printed nothing, so requests carry a placeholder key| Run the command directly to see why it fails, and re-authenticate with your credential provider if it reports an expired session; see [the error reference](</docs/en/errors#your-apikeyhelper-script-is-failing>) -`Unable to connect to API (ConnectionRefused)` when nothing answers at the address, `Unable to connect to API (FailedToOpenSocket)` when the hostname doesn’t resolve, or `(ECONNREFUSED)` from npm installs, often after a silent pause while Claude Code [retries with backoff](</docs/en/errors#automatic-retries>)| Nothing answered at the base URL: the address is wrong, or a VPN or firewall blocks the path to the gateway| Run the curl test above, which fails immediately with the same cause, and confirm the URL and network path with your gateway team +`Your apiKeyHelper script is failing`| The command in the [`apiKeyHelper`](</docs/en/settings#available-settings>) setting didn’t produce a usable key, so requests carry a placeholder key| Run the command directly to see why it fails, and re-authenticate with your credential provider if it reports an expired session; see [the error reference](</docs/en/errors#your-apikeyhelper-script-is-failing>) +`Connection refused — a firewall or proxy may be blocking it (ConnectionRefused)` when nothing answers at the address, or `Can't reach the API server — check your internet or DNS (ENOTFOUND)` when the hostname doesn’t resolve, often after a silent pause while Claude Code [retries with backoff](</docs/en/errors#automatic-retries>). The code in parentheses varies; [Unable to connect to API](</docs/en/errors#unable-to-connect-to-api>) covers the code spellings and the earlier wording| Nothing answered at the base URL: the address is wrong, or a VPN or firewall blocks the path to the gateway| Run the curl test above, which fails immediately with the same cause, and confirm the URL and network path with your gateway team `API returned an empty or malformed response (HTTP 200)`| The gateway or an intermediate proxy returned a non-API response, often an HTML error or login page| Test with the curl request above; fix the gateway route that returns non-JSON `400` errors naming `context_management`, `Extra inputs are not permitted`, or other unrecognized fields| The gateway forwards requests to an upstream that rejects fields Claude Code sends to Anthropic-format endpoints| Set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`, which suppresses most pre-release fields; see [feature pass-through](</docs/en/llm-gateway-protocol#feature-pass-through>). Some betas aren’t gated by this flag; for those, set the matching `CLAUDE_CODE_USE_*` provider variable so Claude Code sends only what that provider accepts `400` errors naming `thinking` or `adaptive`, such as `Input tag 'adaptive' found`| The upstream model build doesn’t accept adaptive reasoning, which Claude Code requests for Claude 4.6 and later models| Upgrade the gateway’s upstream. On Opus 4.6 and Sonnet 4.6, `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` works instead. The [model configuration](</docs/en/model-config>) capability variables apply only to the provider configurations, such as `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_VERTEX`, not behind an `ANTHROPIC_BASE_URL` gateway
modified Gateway protocol reference View current →
--- a/llm-gateway-protocol.md +++ b/llm-gateway-protocol.md @@ -146,7 +146,12 @@ Disable pre-release capabilities -`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` stops Claude Code from sending pre-release capabilities and their body fields on every provider, including context management and the beta tool fields. It doesn’t affect adaptive reasoning, which is selected by model rather than by beta, and it never suppresses the OAuth capability that subscription authentication requires. The set of capabilities Claude Code sends grows over releases. For current beta header strings, see the [beta headers reference](<https://platform.claude.com/docs/en/api/beta-headers>); test your gateway against new Claude Code releases rather than pinning to an observed list. +`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` stops Claude Code from sending pre-release capabilities and their body fields on every provider, including context management and the beta tool fields. The variable doesn’t affect adaptive reasoning, which is selected by model rather than by beta. It never suppresses the OAuth capability that subscription authentication requires. On Claude Code v2.1.227 or later, your organization can keep [MCP tool search](</docs/en/mcp#scale-with-mcp-tool-search>) on under this variable through [managed settings](</docs/en/settings#settings-files>). What Claude Code sends with that override in place depends on how you connect: + + * On a direct connection, or through a gateway set with `ANTHROPIC_BASE_URL`, Claude Code keeps sending the tool-search beta header, `defer_loading` tool fields, and `tool_reference` blocks, and strips the rest + * On a cloud provider, or signed in through a [Claude apps gateway](</docs/en/claude-apps-gateway>), the override has no effect + +The set of capabilities Claude Code sends grows over releases. For current beta header strings, see the [beta headers reference](<https://platform.claude.com/docs/en/api/beta-headers>); test your gateway against new Claude Code releases rather than pinning to an observed list. ## @@ -196,7 +201,7 @@ Picker entries and caching -The picker is the interactive model list that opens when a developer runs `/model` in Claude Code. Each discovered entry is labeled “From gateway” and uses `display_name` when provided. The [`availableModels` managed setting](</docs/en/settings#available-settings>) bounds what discovery can add. A discovered ID is skipped when it exactly matches a row already in the picker, or when both the discovered and existing IDs resolve to [Fable](</docs/en/model-config#work-with-fable-5>). As of Claude Code v2.1.197, a discovered explicit ID is also folded into a built-in entry when both resolve to the same model. Built-in rows are keyed on aliases such as `sonnet`, so a discovered explicit ID of the model the alias currently resolves to, such as `claude-sonnet-5`, collapses into the `sonnet` row, while an ID the alias doesn’t resolve to, such as `claude-sonnet-4-6`, still adds its own “From gateway” row alongside the built-in entry. Results are cached to `~/.claude/cache/gateway-models.json`, or `%USERPROFILE%\.claude\cache\gateway-models.json` on Windows, and refreshed on each startup. If you set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>), the cache lives under that directory instead. If the request fails or the gateway doesn’t implement `/v1/models`, the picker falls back to the cached list from the previous startup or to the built-in model list. If your gateway serves Claude models under aliases that don’t match the discovery filter, developers can add those aliases manually with the [model configuration](</docs/en/model-config>) variables. +The picker is the interactive model list that opens when a developer runs `/model` in Claude Code. Each discovered entry is labeled “From gateway” and uses `display_name` when provided. The [`availableModels` managed setting](</docs/en/settings#available-settings>) bounds what discovery can add. A discovered ID is skipped when it exactly matches a row already in the picker, or when both the discovered and existing IDs resolve to [Fable](</docs/en/model-config#work-with-fable-5>). A discovered explicit ID is also folded into a built-in entry when both resolve to the same model. Built-in rows are keyed on aliases such as `sonnet`, so a discovered explicit ID of the model the alias currently resolves to, such as `claude-sonnet-5`, collapses into the `sonnet` row, while an ID the alias doesn’t resolve to, such as `claude-sonnet-4-6`, still adds its own “From gateway” row alongside the built-in entry. Before v2.1.197, Claude Code didn’t fold explicit IDs into built-in entries, so a discovered ID such as `claude-sonnet-5` added its own “From gateway” row alongside the `sonnet` row. Results are cached to `~/.claude/cache/gateway-models.json`, or `%USERPROFILE%\.claude\cache\gateway-models.json` on Windows, and refreshed on each startup. If you set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>), the cache lives under that directory instead. If the request fails or the gateway doesn’t implement `/v1/models`, the picker falls back to the cached list from the previous startup or to the built-in model list. If your gateway serves Claude models under aliases that don’t match the discovery filter, developers can add those aliases manually with the [model configuration](</docs/en/model-config>) variables. ##
modified Roll out an LLM gateway for your organization View current →
--- a/llm-gateway-rollout.md +++ b/llm-gateway-rollout.md @@ -163,7 +163,7 @@ `apiKeyHelper`, or a credential in `ANTHROPIC_AUTH_TOKEN` or `ANTHROPIC_API_KEY`| Authenticates each request to the gateway. The helper runs a command to fetch the key; the variables hold a static key, sent as `Authorization: Bearer` and `x-api-key` respectively| Always; one of the three `ANTHROPIC_CUSTOM_HEADERS`| Adds extra HTTP headers to every API request| Your gateway requires a tenant or routing header on every request `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY`| Queries the gateway’s `/v1/models` at startup and adds the returned names to the `/model` picker| Your gateway serves `/v1/models` and you want developers’ pickers populated from it -`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`| Stops Claude Code sending pre-release capability headers and body fields| Your gateway forwards to an Amazon Bedrock or Google Cloud’s Agent Platform upstream that rejects beta fields; see Gateway requirements +`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`| Stops Claude Code sending pre-release capability headers and body fields. [Disable pre-release capabilities](</docs/en/llm-gateway-protocol#disable-pre-release-capabilities>) covers the exact scope| Your gateway forwards to an Amazon Bedrock or Google Cloud’s Agent Platform upstream that rejects beta fields. See Gateway requirements `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS` or `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK`| Restores [fast mode](</docs/en/fast-mode>) when its availability check, which calls `api.anthropic.com` directly rather than following `ANTHROPIC_BASE_URL`, fails, is intercepted, or is skipped for lack of an Anthropic credential| Your organization uses fast mode, and developers authenticate with `ANTHROPIC_AUTH_TOKEN` alone, with a gateway-issued key in `ANTHROPIC_API_KEY` or from an `apiKeyHelper`, or your network blocks or intercepts direct requests to `api.anthropic.com`; [use fast mode behind proxies and LLM gateways](</docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways>) covers which of the two variables matches your configuration `ANTHROPIC_MODEL` or [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](</docs/en/model-config>)| Set which model name Claude Code requests for the main session and for background traffic| Your gateway routes model names that don’t match Claude Code’s defaults, or you route [background functionality](</docs/en/costs#background-token-usage>) to a different model. Route both the override names and the built-in model IDs Claude Code requests when no override is set, since some background sub-calls request a built-in ID regardless of the override; [model configuration](</docs/en/model-config>) covers which model each part of a session uses `ANTHROPIC_BEDROCK_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL`, `ANTHROPIC_FOUNDRY_BASE_URL`, or `ANTHROPIC_AWS_BASE_URL` with the [variables for that provider](</docs/en/llm-gateway-connect#route-to-a-cloud-provider-through-a-gateway>)| Point Claude Code at the gateway through a provider-specific base URL. Amazon Bedrock and Google Cloud’s Agent Platform also switch to those providers’ native request format| Your gateway fronts Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or the Claude Platform on AWS; see [API formats](</docs/en/llm-gateway-protocol#api-formats>)
modified Migrate to Claude Agent SDK View current →
--- a/migration-guide.md +++ b/migration-guide.md @@ -86,19 +86,7 @@ # After from claude_agent_sdk import query, ClaudeAgentOptions -**4\. Update type names:** Change `ClaudeCodeOptions` to `ClaudeAgentOptions`: - - # Before - from claude_code_sdk import query, ClaudeCodeOptions - - options = ClaudeCodeOptions(model="claude-opus-4-7") - - # After - from claude_agent_sdk import query, ClaudeAgentOptions - - options = ClaudeAgentOptions(model="claude-opus-4-7") - -**5\. Reviewbreaking changes** Make any code changes needed to complete the migration. +**4\. Reviewbreaking changes** Make any code changes needed to complete the migration. ## @@ -106,7 +94,7 @@ Breaking changes -To improve isolation and explicit configuration, Claude Agent SDK v0.1.0 introduces breaking changes for users migrating from Claude Code SDK. Review this section carefully before migrating. +To improve isolation and explicit configuration, Claude Agent SDK v0.1.0 introduces breaking changes for users migrating from Claude Code SDK. ###
modified Claude Code on mobile View current →
--- a/mobile.md +++ b/mobile.md @@ -42,7 +42,7 @@ [Remote Control](</docs/en/remote-control>)| A Claude Code session running on your computer| The work needs your local filesystem, tools, or MCP servers. [Dispatch](</docs/en/desktop#sessions-from-dispatch>)| The Desktop app on your computer| You want to message a task and let Dispatch decide how to run it. Requires a Pro or Max plan. -If your computer will be off, use cloud sessions: they run in the cloud and continue with your laptop closed. Remote Control and Dispatch drive your own machine, so it needs to stay on with Claude Code or the Desktop app running. If your machine sleeps during a Remote Control session, the session reconnects when it comes back online. For a fuller comparison that also covers Channels, Slack, and scheduled tasks, see [work when you are away from your terminal](</docs/en/platforms#work-when-you-are-away-from-your-terminal>). Cloud sessions and Remote Control run from the **Code** tab and are covered below. For Dispatch, which you message as a task in the app, see [sessions from Dispatch](</docs/en/desktop#sessions-from-dispatch>). +If your computer will be off, use cloud sessions, which run in the cloud and continue with your laptop closed. Remote Control and Dispatch drive your own machine, so it needs to stay on with Claude Code or the Desktop app running. If your machine sleeps during a Remote Control session, Claude Code reconnects when the machine comes back online. For a fuller comparison, see [work when you are away from your terminal](</docs/en/platforms#work-when-you-are-away-from-your-terminal>). Cloud sessions and Remote Control run from the **Code** tab. For Dispatch, which you message as a task in the app, see [sessions from Dispatch](</docs/en/desktop#sessions-from-dispatch>). ### @@ -58,7 +58,7 @@ Continue a local session with Remote Control -Remote Control connects the Claude app to a Claude Code session running on your machine, so code execution and filesystem access stay local while you drive the session from your phone. Start the session on your computer with `claude remote-control`, or run `/remote-control` in a session that’s already open. Then scan the session QR code the terminal can display, or open the Claude app, tap **Code** , and pick the session from the list. See [connect from another device](</docs/en/remote-control#connect-from-another-device>) for each option. Attachments you add in the Claude app reach the local session too: Claude Code downloads the image or file to your machine and passes it to Claude as an `@` file reference. For requirements, invocation modes, and troubleshooting, see the [Remote Control overview](</docs/en/remote-control>). +Remote Control connects the Claude app to a Claude Code session running on your machine, so code execution and filesystem access stay local while you drive the session from your phone. Start the session on your computer with `claude remote-control`, or run `/remote-control` in a session that’s already open. Then scan the session QR code the terminal can display, or open the Claude app, tap **Code** , and pick the session from the list. See [connect from another device](</docs/en/remote-control#connect-from-another-device>) for each option. Attachments you add in the Claude app reach the local session too. Claude sees attached photos directly as part of your message. Claude Code downloads other files to your machine and passes them to Claude as `@` file references. For requirements, invocation modes, and troubleshooting, see the [Remote Control overview](</docs/en/remote-control>). ###
modified Model configuration View current →
Show diff (223 lines)
--- a/model-config.md +++ b/model-config.md @@ -23,7 +23,7 @@ Model aliases -Model aliases provide a convenient way to select model settings without remembering exact version numbers: +Use a model alias to select model settings without remembering exact version numbers: Model alias| Behavior ---|--- @@ -67,6 +67,19 @@ On the Anthropic API, the `/model` picker lists Fable 5 only after the server reports it available for your organization. When you type `/model fable`, Claude Code checks availability with the server directly, so the selection can succeed before the picker lists the entry. +#### + +​ + +Fable 5 and usage credits + +Depending on your plan and seat tier, Fable 5 usage can bill to [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) instead of drawing on your plan’s included limits. When it does, the `/model` picker shows “Requires usage credits” on the Fable 5 row. To manage usage credits, see [Add usage credits to your subscription](</docs/en/costs#add-usage-credits-to-your-subscription>). In interactive sessions, Claude Code shows a consent prompt before a Fable 5 request bills usage credits. Members of Enterprise plans with organization billing don’t see the prompt. You can continue on Fable 5 using usage credits or switch to your default model. You can also dismiss the prompt: + + * In the `/model` picker, you keep your current model. + * Mid-session, Claude Code continues the turn on your default model. + +After you choose to continue on Fable 5 using usage credits, Claude Code doesn’t show the prompt again. In [non-interactive mode](</docs/en/headless>) with the `-p` flag and through the Agent SDK, Claude Code never shows the consent prompt. When a Fable 5 request there would bill to usage credits, Claude Code bills it without asking. + ### ​ @@ -127,14 +140,14 @@ On the Anthropic API and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), a model family alias, `opus`, `sonnet`, `haiku`, or `fable`, resolves to the newest version of its family that the allowlist permits. When the allowlist pins specific versions, for example `["sonnet", "claude-opus-4-6"]`, both `/model opus` and `--model opus` select Claude Opus 4.6, the newest permitted Opus, and show a notice naming both the requested and substituted models. Before v2.1.205, an alias whose newest released version was outside the list was rejected or replaced like any other blocked selection, even when the list permitted an older version. The substitution needs a permitted version to land on: when the allowlist permits no version of the alias’s family, the alias follows the rejection and replacement behavior below like any other blocked value. Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and [Mantle](</docs/en/amazon-bedrock#use-the-mantle-endpoint>) use provider-specific deployment IDs rather than Anthropic model IDs, so a blocked alias there follows the same behavior below. Claude Code handles any other blocked selection according to where the model was set: - * **`/model`** : the switch is rejected with an error - * **`--model` flag, `ANTHROPIC_MODEL`, or the `model` setting**: the value is replaced at startup with a warning naming both the requested and substituted models, and the session starts on the default model - * **Subagent or teammate override** : the override falls back to the [subagent’s inherited model](</docs/en/sub-agents#choose-a-model>) or the [default teammate model](</docs/en/agent-teams#specify-teammates-and-models>) rather than failing the request. When the blocked value is the **Default teammate model** setting itself, Claude Code runs the teammate on your provider’s default Opus model, or on the lead’s model when the allowlist blocks that too. On the Anthropic API and Claude Platform on AWS, a blocked family alias instead follows the substitution above, so the subagent or teammate runs on the newest permitted version of its family; on the providers with provider-specific IDs, the alias falls back like any other blocked value. Before v2.1.222, a blocked family alias fell back like any other blocked value on every provider + * **`/model`** : Claude Code rejects the switch with an error + * **`--model` flag, `ANTHROPIC_MODEL`, or the `model` setting**: Claude Code replaces the value at startup with a warning naming both the requested and substituted models, and the session starts on the default model + * **Subagent or teammate override** : Claude Code falls back to the [subagent’s inherited model](</docs/en/sub-agents#choose-a-model>) or the [default teammate model](</docs/en/agent-teams#specify-teammates-and-models>) rather than failing the request. In interactive sessions, Claude Code warns you when it substitutes a subagent’s model, by this fallback or by the newest-permitted-version substitution above, naming the requested and substituted models; it doesn’t report a teammate’s fallback. When the blocked value is the **Default teammate model** setting itself, Claude Code runs the teammate on your provider’s default Opus model, or on the lead’s model when the allowlist blocks that too. Where the newest-permitted-version substitution above operates, a blocked family alias follows it instead; before v2.1.222, an alias fell back like any other blocked value on every provider * **Skill or command override** : Claude Code ignores the override, including a blocked family alias, and the skill or command runs on the session model. A skill or command that [runs in a subagent](</docs/en/skills#run-skills-in-a-subagent>) follows the subagent behavior above instead * **`advisorModel` setting**: the advisor is disabled for the session * **`--advisor` flag**: Claude Code exits with an error at launch -Excluded models are hidden from the `/model` picker. A full model ID in the list that has no built-in picker row, such as an older version that the list pins, appears in the `/model` picker as its own labeled row. Before v2.1.199, such an ID was selectable only by typing `/model <id>`. Model changes that Claude Code makes on your behalf are checked the same way: +Claude Code hides excluded models from the `/model` picker. A full model ID in the list that has no built-in picker row, such as an older version that the list pins, appears in the `/model` picker as its own labeled row. Before v2.1.199, such an ID was selectable only by typing `/model <id>`. Model changes that Claude Code makes on your behalf are checked the same way: * **Fallback model chains** : entries outside the allowlist are dropped * **Plan-mode upgrades** : on the Anthropic API and Claude Platform on AWS, an upgrade such as `opusplan` to an excluded model uses the newest permitted version of the upgrade family. On providers with provider-specific model IDs, and when no version is permitted, the upgrade is skipped and planning continues on the session’s model @@ -314,7 +327,7 @@ Fallback model chains -When the primary model is overloaded, unavailable, or returns another non-retryable server error, Claude Code can switch to a fallback model instead of failing the request. Authentication, billing, rate-limit, request-size, and transport errors never trigger a switch; those follow their normal retry and error handling. Configure one or more fallback models and Claude Code tries them in order, showing a notice when it switches. The switch lasts for the current turn only, so your next message tries the primary model first again. Chains are capped at three models after duplicate removal, and extra entries are ignored. Set a chain for one session with the `--fallback-model` flag, which accepts a comma-separated list: +When the primary model is overloaded, unavailable, or returns another non-retryable server error, Claude Code can switch to a fallback model instead of failing the request. Authentication, billing, rate-limit, request-size, and transport errors never trigger a switch; those follow their normal retry and error handling. Configure one or more fallback models and Claude Code tries them in order, showing a notice when it switches. The switch lasts for the current turn only, so your next message tries the primary model first again. Claude Code caps chains at three models after duplicate removal and ignores extra entries. Set a chain for one session with the `--fallback-model` flag, which accepts a comma-separated list: claude --fallback-model sonnet,haiku @@ -324,9 +337,9 @@ "fallbackModel": ["claude-sonnet-5", "claude-haiku-4-5"] } -The `--fallback-model` flag takes precedence over the `fallbackModel` setting. Each entry accepts a model name or alias, and `"default"` expands to the default model. Claude Code doesn’t confirm the chain at startup and `/status` doesn’t display it. The notice shown when a switch happens is the first visible sign that a fallback is configured. When a request fails over, Claude Code tries each entry in order until one accepts it. An entry that can’t be reached either, such as a retired model pinned in settings, fails over to the next one the same way. Two kinds of entry are removed before that walk starts: - - * **Outside the allowlist** : any entry not permitted by `availableModels` is dropped when Claude Code reads the chain. +The `--fallback-model` flag takes precedence over the `fallbackModel` setting. Each entry accepts a model name or alias, and `"default"` expands to the default model. Claude Code doesn’t confirm the chain at startup and `/status` doesn’t display it. The notice shown when a switch happens is the first visible sign that a fallback is configured. When a request fails over, Claude Code tries each entry in order until one accepts it. An entry that can’t be reached either, such as a retired model pinned in settings, fails over to the next one the same way. Claude Code removes two kinds of entry before that walk starts: + + * **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. ### @@ -358,11 +371,11 @@ To decide what happens each time a request is flagged, rather than switching automatically, run `/config` and turn off **Switch models when a message is flagged** , or set [`switchModelsOnFlag`](</docs/en/settings#available-settings>) to `false` in your settings file. A flagged request then pauses the session with two options: switch to the fallback model, or edit the prompt and retry on the current model. Some cases behave differently: - * When the flagged category has no fallback model, such as a biology flag on Opus 5, the prompt is not shown and the request ends with the refusal. + * When the flagged category has no fallback model, such as a biology flag on Opus 5, Claude Code doesn’t show the prompt and the request ends with the refusal. * If both models flag the same request, you can edit the prompt and retry, or start a new session. * On mobile [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions, editing and retrying is not supported. Switch models, or continue the session from a desktop browser or the desktop app. * In [non-interactive mode](</docs/en/cli-reference#cli-flags>) and SDK integrations that can’t show the prompt, a flagged request ends the turn with a refusal instead. - * When the fallback target is blocked by `availableModels`, the prompt is not shown. The flagged request ends with the refusal, the same as automatic fallback when the target is blocked. + * When the fallback target is blocked by `availableModels`, Claude Code doesn’t show the prompt. The flagged request ends with the refusal, the same as automatic fallback when the target is blocked. #### @@ -399,7 +412,7 @@ Opus 5, Sonnet 5, Opus 4.8, and Opus 4.7| `low`, `medium`, `high`, `xhigh`, `max` Opus 4.6 and Sonnet 4.6| `low`, `medium`, `high`, `max` -If you set a level the active model does not support, Claude Code falls back to the highest supported level at or below the one you set. For example, `xhigh` runs as `high` on Opus 4.6. Your organization can also cap which levels are available for a model; see Organization effort limits. The default effort is `high` on every model that supports effort, except Opus 4.7, which defaults to `xhigh`. When you first run Fable 5, Opus 4.8, or Opus 4.7, Claude Code applies that model’s default effort even if you previously set a different level for another model, and holds it across sessions until you make an explicit effort choice, such as running `/effort` in an interactive session or launching with `--effort`. Opus 5 has no such hold: a level you previously set carries over. `low`, `medium`, `high`, and `xhigh` persist across sessions when you set them in an interactive session. `max` provides the deepest reasoning and applies to the current session only, except when set through the `CLAUDE_CODE_EFFORT_LEVEL` environment variable. A level set with `/effort` in [non-interactive mode](</docs/en/headless>), with the `-p` flag, applies to the current session only and isn’t saved as your default. It also can’t release the model-default hold: while the hold is in force, a non-interactive `/effort` reports `Not applied`, so pass `--effort` at launch instead. The `/effort` menu also offers `ultracode`. Ultracode is a Claude Code setting rather than a model effort level: it sends `xhigh` to the model and additionally has Claude orchestrate [dynamic workflows](</docs/en/workflows>) for substantive tasks. It applies to the current session only. You can turn on ultracode through any of the following: +If you set a level the active model does not support, Claude Code falls back to the highest supported level at or below the one you set. For example, `xhigh` runs as `high` on Opus 4.6. Your organization can also cap which levels are available for a model; see Organization effort limits. The default effort is `high` on every model that supports effort, except Opus 4.7, which defaults to `xhigh`. When you first run Fable 5, Opus 4.8, or Opus 4.7, Claude Code applies that model’s default effort even if you previously set a different level for another model, and holds it across sessions until you make an explicit effort choice, such as running `/effort` in an interactive session or launching with `--effort`. Opus 5 has no such hold: a level you previously set carries over. `low`, `medium`, `high`, and `xhigh` persist across sessions when you set them in an interactive session. `max` provides the deepest reasoning. Unless you set it through the `CLAUDE_CODE_EFFORT_LEVEL` environment variable, `max` applies to the current session only. A level set with `/effort` in [non-interactive mode](</docs/en/headless>), with the `-p` flag, applies to the current session only and isn’t saved as your default. It also can’t release the model-default hold: while the hold is in force, a non-interactive `/effort` reports `Not applied`, so pass `--effort` at launch instead. The `/effort` menu also offers `ultracode`. Ultracode is a Claude Code setting rather than a model effort level: it sends `xhigh` to the model and additionally has Claude orchestrate [dynamic workflows](</docs/en/workflows>) for substantive tasks. It applies to the current session only. You can turn on ultracode through any of the following: * **`/effort`** : run `/effort ultracode`, or select it from the menu * **`--effort` flag**: launch with `claude --effort ultracode`, which starts the session at `xhigh` effort with ultracode on @@ -432,7 +445,7 @@ Use ultrathink for one-off deep reasoning -Include `ultrathink` anywhere in your prompt to request deeper reasoning on that turn without changing your session effort setting. Claude Code recognizes the keyword and adds an in-context instruction. The effort level sent to the API is unchanged. Other phrases such as “think”, “think hard”, and “think more” are passed through as ordinary prompt text and are not recognized as keywords. +Include `ultrathink` anywhere in your prompt to request deeper reasoning on that turn without changing your session effort setting. Claude Code recognizes the keyword and adds an in-context instruction. The effort level sent to the API is unchanged. Claude Code passes other phrases such as “think”, “think hard”, and “think more” through as ordinary prompt text and doesn’t recognize them as keywords. #### @@ -473,7 +486,7 @@ Set the global default| Run `/config` and toggle thinking mode. Saved as `alwaysThinkingEnabled` in `~/.claude/settings.json` Disable regardless of effort| Set [`MAX_THINKING_TOKENS=0`](</docs/en/env-vars>), which turns thinking off on the Anthropic API except on Fable 5. On [third-party providers](</docs/en/third-party-integrations>) this omits the `thinking` parameter instead, and adaptive-reasoning models may still think. Other values apply only with a fixed thinking budget -Thinking cannot be turned off on Fable 5. The session toggle, `alwaysThinkingEnabled`, and `MAX_THINKING_TOKENS=0` have no effect there, and Fable 5 decides per step how much to think based on the effort level. Thinking output is collapsed by default. Press `Ctrl+O` to toggle verbose mode and see the reasoning as gray italic text. Interactive sessions on the Anthropic API receive redacted thinking blocks by default, so set `showThinkingSummaries: true` in [settings](</docs/en/settings>) if you want the full summaries available when you expand. You are charged for all thinking tokens generated, even when collapsed or redacted. +Thinking cannot be turned off on Fable 5. The session toggle, `alwaysThinkingEnabled`, and `MAX_THINKING_TOKENS=0` have no effect there, and Fable 5 decides per step how much to think based on the effort level. Claude Code collapses thinking output by default. Press `Ctrl+O` to toggle verbose mode and see the reasoning as gray italic text. Interactive sessions on the Anthropic API receive redacted thinking blocks by default, so set `showThinkingSummaries: true` in [settings](</docs/en/settings>) if you want the full summaries available when you expand. You are charged for all thinking tokens generated, even when collapsed or redacted. ### @@ -489,7 +502,12 @@ Pro| Requires [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>)| Requires [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) API and pay-as-you-go| Full access| Full access -To disable 1M context entirely, set `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`. This removes 1M model variants from the model picker. See [environment variables](</docs/en/env-vars>). The 1M context window uses standard model pricing with no premium for tokens beyond 200K. For plans where extended context is included with your subscription, usage remains covered by your subscription. For plans that access extended context through usage credits, tokens are billed to usage credits. If your account supports 1M context, the option appears in the `/model` picker in the latest versions of Claude Code. If you don’t see it, try restarting your session. You can also use the `[1m]` suffix with model aliases or full model names: +To turn off 1M context, set `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`. Claude Code removes 1M model variants from the model picker. On models with a native 1M window, such as Sonnet 5 and Fable 5, it also treats the model as having a 200K context window: + + * With auto-compaction on, sessions compact at the 200K boundary through auto-compaction. Setting the auto-compact window above 200K doesn’t lift the hold, because Claude Code caps that window at the model’s context window. + * With auto-compaction off, sessions stop at the 200K boundary with a [`Prompt is too long` error](</docs/en/errors#prompt-is-too-long>) instead of compacting. + +Before v2.1.223, Claude Code held only Sonnet 5, Opus 4.8, and Opus 5 sessions to 200K. See [environment variables](</docs/en/env-vars>). The 1M context window uses standard model pricing with no premium for tokens beyond 200K. For plans where extended context is included with your subscription, usage remains covered by your subscription. For plans that access extended context through usage credits, tokens are billed to usage credits. If your account supports 1M context, the option appears in the `/model` picker in the latest versions of Claude Code. If you don’t see it, try restarting your session. You can also use the `[1m]` suffix with model aliases or full model names: # Use the opus[1m] or sonnet[1m] alias /model opus[1m] @@ -504,10 +522,66 @@ Sonnet 5 context window -On the Anthropic API, Sonnet 5 always runs with the 1M context window. There is no 200K variant, no `[1m]` suffix to select, and no usage credits required on any plan. Sessions auto-compact before the window fills, at about 967K tokens by default; set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>) to choose a different threshold. Two configurations budget the window at 200K instead and auto-compact at that boundary: +On the Anthropic API, Sonnet 5 always runs with the 1M context window. There is no 200K variant, no `[1m]` suffix to select, and no usage credits required on any plan. Sessions auto-compact before the window fills, at about 967K tokens by default; set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>) to choose a different threshold. Two configurations budget the window at 200K instead: * **LLM gateway** : when `ANTHROPIC_BASE_URL` points at a [gateway](</docs/en/llm-gateway>), Claude Code can’t verify 1M support. To use the full window, select Sonnet 5 (1M context) in the model picker, which maps to `sonnet[1m]`. - * **`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`** : treats Sonnet 5 sessions as having a 200K window, for deployments that need to cap context. + * **`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`** : holds sessions on every model with a native 1M window to a 200K window; see Extended context for how the hold is enforced. Useful for deployments that need to cap context. + +## + +​ + +Context window and auto-compaction + +The auto-compact window is how full the context window can get before Claude Code compacts the conversation. For what compaction keeps and drops per mechanism, see [What survives compaction](</docs/en/context-window#what-survives-compaction>). + +### + +​ + +Set the auto-compact window + +You can set the auto-compact window in three places: + + * **For this session and later ones** : run `/autocompact` with a value, like `/autocompact 500k`. Claude Code saves it to your user settings as [`autoCompactWindow`](</docs/en/settings#available-settings>) and applies it to the current session; if a higher-priority [settings scope](</docs/en/settings#settings-precedence>) such as managed settings sets the key, the command saves your value but the session keeps that scope’s window, and the command says so. Run `/autocompact auto` to return to the window tuned for your model. + * **For one launch** : pass [`--autocompact`](</docs/en/cli-reference#cli-flags>) when starting Claude Code. The flag overrides your saved setting for that launch without changing it, and `claude --autocompact auto` runs the session at the tuned window even if your saved setting has a value. Unlike `/autocompact`, the flag isn’t preempted by a higher-priority settings scope such as managed settings. + * **In scripts and cloud environments** : set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>). While it’s set, it takes precedence over the command, the flag, and the setting, and `/autocompact` reports the override instead of changing the window. + +The command and the flag accept a window size from 100K to 1M tokens, in any of these forms: + + * A plain token count, such as `200000` + * A `k` or `M` suffix, such as `500k` or `1M` + * A bare number from 100 to 1000, meaning thousands, so `200` sets 200,000 + +The environment variable accepts only the plain token count. Claude Code caps the window at the model’s context window. + +### + +​ + +Default auto-compact thresholds + +If you don’t set an auto-compact window, Claude Code compacts when the conversation reaches the model’s context limit, except in these sessions: + + * [Cloud sessions](</docs/en/claude-code-on-the-web>) compact as the conversation approaches the model’s limit + * Sonnet 4.6 and Opus 4.6 without extended context compact at the 200K boundary, and so do Opus 4.8 and Opus 5 when they run with a 200K context window, such as on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry + * When you set [`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`](</docs/en/env-vars>), models with a native 1M window, such as Sonnet 5 and Fable 5, compact at the 200K boundary + * Sonnet 5 compacts at the threshold for its configuration + * Sessions on a model ID Claude Code doesn’t recognize, such as an [LLM gateway](</docs/en/llm-gateway>) alias, compact at the context window Claude Code assumes for the ID; see Correct the window for a gateway or custom model ID + +### + +​ + +Correct the window for a gateway or custom model ID + +On an [LLM gateway](</docs/en/llm-gateway>) or other custom deployment, Claude Code can assume a context window for the model ID that differs from the model’s real window, whether or not it resolves the ID to a Claude model. [`CLAUDE_CODE_MAX_CONTEXT_TOKENS`](</docs/en/env-vars>) declares the window Claude Code should assume instead. How the variable applies depends on the ID. An unrecognized ID, an unrecognized `[1m]` ID, and an ID that starts with `claude-` or resolves to a Claude model are three separate cases: + + * If the ID doesn’t start with `claude-` or contain `[1m]`, in any casing, and Claude Code can’t resolve it to a Claude model, the variable applies directly and proactive compaction continues at the declared window. + * If the ID doesn’t start with `claude-` but contains `[1m]`, in any casing, and Claude Code can’t resolve it to a Claude model, Claude Code assumes a 1M window for it and the variable doesn’t apply on its own. To correct the window while keeping proactive compaction, also set [`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`](</docs/en/env-vars>). With a declared window above 200K, Claude Code then shows a [startup warning](</docs/en/errors#the-200k-limit-isnt-enforced>) that the 200K limit isn’t enforced. The warning is expected in this configuration. + * If the ID starts with `claude-` in any casing or resolves to a Claude model, the variable takes effect only when [`DISABLE_COMPACT`](</docs/en/env-vars>) is also set, which disables all compaction. For example, Claude Code resolves an ID that contains a Claude model name, such as `anthropic/claude-opus-4-8` or `us.anthropic.claude-…-v1:0`, to that model. This includes IDs that also contain `[1m]`: Claude Code resolves `claude-opus-4-8[1m]` to Opus 4.8 even with `CLAUDE_CODE_DISABLE_1M_CONTEXT` set. + +For a model ID Claude Code doesn’t recognize, set [`CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT=1`](</docs/en/env-vars>) to have Claude Code compact only after the API rejects the conversation with Anthropic’s too-long error; that recovery doesn’t run when a gateway [rewrites the error](</docs/en/llm-gateway-connect#troubleshoot-gateway-errors>). ## @@ -532,7 +606,7 @@ export ANTHROPIC_CUSTOM_MODEL_OPTION_NAME="Opus via Gateway" export ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION="Custom deployment routed through the internal LLM gateway" -The custom entry appears at the bottom of the `/model` picker. `ANTHROPIC_CUSTOM_MODEL_OPTION_NAME` and `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION` are optional. If omitted, the model ID is used as the name and the description defaults to `Custom model (<model-id>)`. Claude Code skips validation for the model ID set in `ANTHROPIC_CUSTOM_MODEL_OPTION`, so you can use any string your API endpoint accepts. When `availableModels` is set, include the custom model ID in the allowlist as well. Otherwise the custom entry is filtered from the picker, and a `--model` selection of it is rejected like any other excluded model. A custom ID that embeds a family name, such as `my-gateway/claude-opus-5`, counts as a specific entry for that family and disables its wildcard, so also list the versions you intend to keep selectable. See Merge behavior. +The custom entry appears at the bottom of the `/model` picker. `ANTHROPIC_CUSTOM_MODEL_OPTION_NAME` and `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION` are optional. If you omit the name, Claude Code uses the model ID; if you omit the description, Claude Code uses `Custom model (<model-id>)`. Claude Code skips validation for the model ID set in `ANTHROPIC_CUSTOM_MODEL_OPTION`, so you can use any string your API endpoint accepts. When `availableModels` is set, include the custom model ID in the allowlist as well. Otherwise Claude Code filters the custom entry from the picker and rejects a `--model` selection of it like any other excluded model. A custom ID that embeds a family name, such as `my-gateway/claude-opus-5`, counts as a specific entry for that family and disables its wildcard, so also list the versions you intend to keep selectable. See Merge behavior. ## @@ -540,7 +614,7 @@ Environment variables -You can use the following environment variables to control the model names that the aliases map to. Each value must be a full model name, or the equivalent identifier for your API provider. +Use the following environment variables to control the model names that the aliases map to. Each value must be a full model name, or the equivalent identifier for your API provider. Environment variable| Description ---|--- @@ -607,7 +681,7 @@ `adaptive_thinking`| Adaptive reasoning that dynamically allocates thinking based on task complexity `interleaved_thinking`| Thinking between tool calls -When `_SUPPORTED_CAPABILITIES` is set, listed capabilities are enabled and unlisted capabilities are disabled for the matching pinned model. When the variable is unset, Claude Code falls back to built-in detection based on the model ID. This example pins Opus to an Amazon Bedrock custom model ARN, sets a friendly name, and declares its capabilities: +When `_SUPPORTED_CAPABILITIES` is set, Claude Code enables the listed capabilities and disables the unlisted ones for the matching pinned model. When the variable is unset, Claude Code falls back to built-in detection based on the model ID. This example pins Opus to an Amazon Bedrock custom model ARN, sets a friendly name, and declares its capabilities: export ANTHROPIC_DEFAULT_OPUS_MODEL='arn:aws:bedrock:us-east-1:123456789012:custom-model/abc' export ANTHROPIC_DEFAULT_OPUS_MODEL_NAME='Opus via Bedrock'
modified Monitoring View current →
Show diff (134 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1,4 +1,4 @@ -Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via the traces protocol. Configure your metrics, logs, and traces backends to match your monitoring requirements. +Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via the traces protocol. ## @@ -22,15 +22,13 @@ # 4. Set authentication (if required) export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token" - # 5. For debugging: reduce export intervals + # 5. For debugging: reduce export intervals, and reset them for production use export OTEL_METRIC_EXPORT_INTERVAL=10000 # 10 seconds (default: 60000ms) export OTEL_LOGS_EXPORT_INTERVAL=5000 # 5 seconds (default: 5000ms) # 6. Run Claude Code claude -The default export intervals are 60 seconds for metrics and 5 seconds for logs. During setup, you may want to use shorter intervals for debugging purposes. Remember to reset these for production use. - To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log for OTel export errors. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). ## @@ -39,7 +37,7 @@ Administrator configuration -Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/settings#settings-files>). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: +Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/settings#settings-files>). See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: { "env": { @@ -51,8 +49,6 @@ "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer example-token" } } - -Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and can’t be overridden by users. Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. @@ -141,7 +137,7 @@ `OTEL_METRICS_INCLUDE_ENTRYPOINT`| Include app.entrypoint attribute in metrics| `false`| `true` `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES`| Include keys from `OTEL_RESOURCE_ATTRIBUTES` as attributes on metric datapoints| `true`| `false` -These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. +Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. ### @@ -387,7 +383,7 @@ export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=prometheus -To send metrics to multiple exporters: +On a [self-hosted environment](</docs/en/self-hosted-environments-reference#pass-through-session-child-metrics>), the session binds port 9464 only at the runner’s default capacity of one. At higher capacity, the runner re-exposes session counters and gauges on its own `/metrics` endpoint instead. To send metrics to multiple exporters: export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=console,otlp @@ -611,8 +607,6 @@ * `message.uuid` on `user_prompt` and `assistant_response` * `request_id` on the API events, persisted as `requestId` on the transcript’s assistant entries * `tool_use_id` on `tool_result` and `tool_decision` events - -`prompt.id` is intentionally excluded from metrics because each prompt generates a unique ID, which would create an ever-growing number of time series. Use it for event-level analysis and audit trails only. #### @@ -1102,6 +1096,30 @@ ​ +Subagent completed event + +Logged when a [subagent](</docs/en/sub-agents>) finishes and returns its result to the conversation that started it. Use it to roll up tool use and run time by subagent type; for token or cost rollups, use the token counter and cost counter filtered to `query_source` `"subagent"`, since this event’s `total_tokens` covers only the final request. The `"subagent"` category also counts requests from agent-based hooks, which emit no subagent event. **Event Name** : `claude_code.subagent_completed` **Attributes** : + + * All standard attributes + * `event.name`: `"subagent_completed"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `agent_type`: The subagent type. Built-in agent names and agents from official-marketplace plugins appear verbatim; other agent names are replaced with `"custom"` unless `OTEL_LOG_TOOL_DETAILS=1` is set + * `agent.source`: Where the agent definition came from: `built-in`, `plugin`, or the settings source that defined a custom agent, such as `userSettings` or `projectSettings` + * `is_built_in`: Whether the subagent is a built-in agent type + * `is_async`: Whether the subagent ran in the [background](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) + * `total_tokens`: The token footprint of the subagent’s final API request: that one request’s input, cache creation, cache read, and output tokens, roughly the subagent’s context size at completion. Not a sum across the run + * `total_tool_uses`: Number of tool calls the subagent made across the whole run + * `duration_ms`: Run time in milliseconds + * `model`: The model the subagent was resolved to run + * `final_model`: The model that produced the subagent’s final response, which differs from `model` after a mid-run switch such as a fallback. Requires Claude Code v2.1.212 or later + * `model_swapped`: Whether more than one model served the subagent’s requests. Requires Claude Code v2.1.212 or later + * `plugin_id_hash`, `plugin.name`: Present for plugin-provided agents. Official-marketplace plugin names appear verbatim; other plugin names are replaced with `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` is set + +#### + +​ + Feedback survey event Logged when a session quality survey is shown or answered. See [Session quality surveys](</docs/en/data-usage#session-quality-surveys>) for what the surveys collect and how to control them. **Event Name** : `claude_code.feedback_survey` **Attributes** : @@ -1115,6 +1133,32 @@ * `survey_type`: Which survey produced the event. `"session"` is the “How is Claude doing?” rating prompt * `response`: The user’s selection on `responded` events * `enabled_via_override`: `true` when [`CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL`](</docs/en/env-vars>) is set. Emitted as a boolean, not a string. Present on `session` survey events. Filter on this attribute to confirm the override is applied across a fleet + +#### + +​ + +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#available-settings>) 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; a managed settings file that itself can’t be read or parsed still pauses the sweep. 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"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `result`: `"complete"` when the sweep ran, `"skipped"` when Claude Code paused it + * `period_days`: The `cleanupPeriodDays` value from merged settings, in days, or `30` when no source sets it. On skipped events, the value the sweep would have used, computed from the settings sources Claude Code could read + * `used_default`: `"true"` when no readable settings source sets `cleanupPeriodDays`, `"false"` otherwise. On complete events, `"true"` means the 30-day default applied + * `skip_reason`: Why Claude Code paused the sweep. Present only when `result` is `"skipped"`: + * `"user_source_disabled"`: User settings are excluded, for example by the [`--setting-sources`](</docs/en/cli-reference#cli-flags>) flag or the SDK’s [`settingSources`](</docs/en/agent-sdk/typescript#options>) option, and no enabled source provides `cleanupPeriodDays` + * `"settings_unknowable"`: A settings file couldn’t be read or parsed, so `cleanupPeriodDays` may be set to a value Claude Code can’t see + * `"settings_invalid_key_set"`: Settings have validation errors and `cleanupPeriodDays` is explicitly set, so falling back to the default could delete files the setting was meant to keep + * `transcripts_deleted`: Number of session transcripts, the top-level `~/.claude/projects/*/*.jsonl` files, that the sweep deleted + * `session_files_deleted`: Number of artifacts the session-files sweep deleted: transcripts plus per-session companion files such as sidecars, recordings, and tool results + * `artifacts_deleted`: Total items the sweep deleted across the data directories it covers, including the session files. Some sweeps count a whole removed directory tree as one item and a few cleanup passes don’t contribute to the counter, so treat the value as a floor rather than an exact file count + * `files_retained_fresh`: Files inspected and left in place because they’re still within the retention period. Only per-file sweeps count these, so the value is a floor; a nonzero value is the normal steady state + * `files_past_cutoff`: Files older than the retention period that the sweep failed to delete, for example because of a permission error or a file held open. A value above zero means files outlived the configured retention period; zero isn’t proof that none did, because a failed removal of a whole directory counts toward `error_count` instead + * `error_count`: Number of errors the sweep encountered while listing or deleting files ##
modified Enterprise network configuration View current →
--- a/network-config.md +++ b/network-config.md @@ -190,6 +190,7 @@ `downloads.claude.ai`| Plugin executable downloads; native installer, native auto-updater, and update version checks `storage.googleapis.com`| Install counts and plugin metadata shown in `/plugin`. Signed [artifact](</docs/en/artifacts>) uploads try this host first; publishing falls back to `api.anthropic.com` when it is blocked `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 `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`
modified Output styles View current →
--- a/output-styles.md +++ b/output-styles.md @@ -18,7 +18,10 @@ Change your output style -Run `/config` and select **Output style** to pick a style from a menu. Your selection is saved to `.claude/settings.local.json` at the [local project level](</docs/en/settings>). +Pick a style in one of these ways: + + * **Terminal** : run `/config` and select **Output style** to pick a style from a menu. Claude Code saves your selection to `.claude/settings.local.json` at the [local project level](</docs/en/settings>). + * **Desktop app** : set the `outputStyle` field in a settings file, for example `.claude/settings.local.json`, the file the terminal menu writes. When you run `/config` there, Claude Code [opens **Settings > Claude Code**](</docs/en/desktop#what%E2%80%99s-not-available-in-desktop>) rather than a menu. The standalone `/output-style` command was deprecated in v2.1.73 and removed in v2.1.91. Use `/config` or edit the `outputStyle` setting directly. @@ -48,7 +51,7 @@ * Project: `.claude/output-styles` * Managed policy: `.claude/output-styles` inside the [managed settings directory](</docs/en/settings#settings-files>) -Project output styles load from every `.claude/output-styles/` between the working directory and the repository root. As of v2.1.178, when more than one of these nested directories defines a style with the same name, Claude Code uses the one closest to the working directory. +Project output styles load from every `.claude/output-styles/` between the working directory and the repository root. When more than one of these nested directories defines a style with the same name, Claude Code uses the one closest to the working directory. 2 @@ -72,7 +75,7 @@ Switch to your style -Run `/config` and select your style under **Output style**. It takes effect after `/clear` or the next time you start a session. +Run `/config` in the terminal and select your style under **Output style** , or set `outputStyle` in a settings file to the style’s name. It takes effect after `/clear` or the next time you start a session. [Plugins](</docs/en/plugins-reference>) can also ship output styles in an `output-styles/` directory.
modified Choose a permission mode View current →
--- a/permission-modes.md +++ b/permission-modes.md @@ -63,7 +63,7 @@ The same `--permission-mode` flag works with `-p` for [non-interactive runs](</docs/en/headless>). -**During a session** : click the mode indicator at the bottom of the prompt box.**As a default** : set `claudeCode.initialPermissionMode` in VS Code settings, or use the Claude Code extension settings panel.The mode indicator shows these labels, mapped to the mode each one applies: +**During a session** : click the mode indicator at the bottom of the prompt box.**As a default** : set `claudeCode.initialPermissionMode` in your VS Code user settings, or use the Claude Code extension settings panel.The mode indicator shows these labels, mapped to the mode each one applies: UI label| Mode ---|--- @@ -73,7 +73,7 @@ Auto| `auto` Bypass permissions| `bypassPermissions` -Auto mode appears in the mode indicator when your account meets every requirement listed in the auto mode section. The `claudeCode.initialPermissionMode` setting does not accept `auto`. To start in auto mode by default, set `defaultMode` in your [user settings](</docs/en/settings#settings-files>) instead. Claude Code ignores `defaultMode: "auto"` in project and local settings.Bypass permissions requires the **Allow dangerously skip permissions** toggle in the extension settings before it appears in the mode indicator.See the [VS Code guide](</docs/en/vs-code>) for extension-specific details. +Auto mode appears in the mode indicator when your account meets every requirement listed in the auto mode section. The `claudeCode.initialPermissionMode` setting does not accept `auto`. To switch a session into auto mode, select **Auto** from the mode indicator.Bypass permissions requires the **Allow dangerously skip permissions** toggle in the extension settings before it appears in the mode indicator.See the [VS Code guide](</docs/en/vs-code>) for extension-specific details. The JetBrains plugin runs Claude Code in the IDE terminal, so switching modes works the same as in the CLI: press `Shift+Tab` to cycle, or pass `--permission-mode` when launching. @@ -141,7 +141,7 @@ Set plan mode as the default -To make plan mode the default for a project, set `defaultMode` in `.claude/settings.json`: +In a session the [VS Code extension](</docs/en/vs-code>) started, a settings-file `defaultMode` doesn’t set the starting mode. Set `claudeCode.initialPermissionMode` to `plan` in your VS Code user settings instead. Elsewhere, to make plan mode the default for a project, set `defaultMode` in `.claude/settings.json`: { "permissions": { @@ -168,7 +168,7 @@ * **Model** : on the Anthropic API and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), Claude Opus 4.6 or later, Sonnet 4.6 or later, or [Fable 5](</docs/en/model-config#work-with-fable-5>). On Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, only Claude Sonnet 5, Opus 4.7 or later, and Fable 5. Older models, including Sonnet 4.5, Opus 4.5, Haiku, and claude-3 models, are not supported on any provider. * **Provider** : available by default on the Anthropic API, Claude Platform on AWS, Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and signed-in Claude apps gateway sessions. -If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage. A separate message that names a model and says auto mode “cannot determine the safety” of an action means a classifier request failed; that failure is usually transient, but on Amazon Bedrock it can repeat until your account can invoke the named model. See the [error reference](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>) for the causes and what to do. If you set `defaultMode: "auto"` in [settings](</docs/en/settings#available-settings>) and the session starts in `default` mode with no error, the setting is likely in `.claude/settings.json` or `.claude/settings.local.json`. Claude Code v2.1.142 and later ignore `auto` from those files so a repository cannot grant itself auto mode. Move it to `~/.claude/settings.json`. +If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage. A separate message that names a model and says auto mode “cannot determine the safety” of an action means a classifier request failed; that failure is usually transient, but on Amazon Bedrock it can repeat until your account can invoke the named model. See the [error reference](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>) for the causes and what to do. If you set `defaultMode: "auto"` in [settings](</docs/en/settings#available-settings>) and the session starts in `default` mode with no error, the setting is likely in `.claude/settings.json` or `.claude/settings.local.json`. Claude Code v2.1.142 and later ignore `auto` from those files so a repository cannot grant itself auto mode. Move it to `~/.claude/settings.json`. In a session the [VS Code extension](</docs/en/vs-code>) started, a settings-file `defaultMode` doesn’t set the starting mode: select the mode from the extension’s mode indicator instead. ### @@ -176,7 +176,7 @@ Auto mode on Bedrock, Agent Platform, or Foundry -On [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, auto mode appears in the `Shift+Tab` cycle by default. Appearing in the cycle doesn’t change the mode a session starts in: sessions still start in your [`defaultMode`](</docs/en/settings#available-settings>), which is Manual unless you change it. Only Claude Sonnet 5, Opus 4.7 or later, and Fable 5 are supported on these providers. To make auto mode the default starting mode, set `"permissions": {"defaultMode": "auto"}` in user or managed settings. The [`/doctor`](</docs/en/commands#all-commands>) checkup proposes this user-settings default on these providers the same way it does on the Anthropic API. To prevent developers from using auto mode, set `disableAutoMode` to `"disable"` in [managed settings](</docs/en/permissions#managed-settings>). This removes `auto` from the `Shift+Tab` cycle and rejects `--permission-mode auto` at startup. In v2.1.158 through v2.1.206, auto mode was off on these providers until you set `CLAUDE_CODE_ENABLE_AUTO_MODE=1`, and Claude Code ignored `defaultMode: "auto"` on these providers unless the variable was also set. The variable is still accepted for compatibility and has no effect from v2.1.207 onward. +On [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, auto mode appears in the `Shift+Tab` cycle by default. Appearing in the cycle doesn’t change the mode a session starts in. Except in sessions the [VS Code extension](</docs/en/vs-code>) starts, where the extension resolves the starting mode, sessions still start in your [`defaultMode`](</docs/en/settings#available-settings>), which is Manual unless you change it. Only Claude Sonnet 5, Opus 4.7 or later, and Fable 5 are supported on these providers. To make auto mode the default starting mode, set `"permissions": {"defaultMode": "auto"}` in user or managed settings. In sessions the VS Code extension starts, select **Auto** from the mode indicator instead. The [`/doctor`](</docs/en/commands#all-commands>) checkup proposes this user-settings default on these providers the same way it does on the Anthropic API. To prevent developers from using auto mode, set `disableAutoMode` to `"disable"` in [managed settings](</docs/en/permissions#managed-settings>). This removes `auto` from the `Shift+Tab` cycle and rejects `--permission-mode auto` at startup. In v2.1.158 through v2.1.206, auto mode was off on these providers until you set `CLAUDE_CODE_ENABLE_AUTO_MODE=1`, and Claude Code ignored `defaultMode: "auto"` on these providers unless the variable was also set. The variable is still accepted for compatibility and has no effect from v2.1.207 onward. ### @@ -281,7 +281,14 @@ When auto mode falls back -Each denied action shows a notification and appears in `/permissions` under the Recently denied tab, where you can press `r` to retry it with a manual approval. If the classifier blocks an action 3 times in a row or 20 times total, auto mode pauses and Claude Code resumes prompting. Approving the prompted action resumes auto mode. These thresholds are not configurable. Any allowed action resets the consecutive counter, while the total counter persists for the session and resets only when its own limit triggers a fallback. In [non-interactive mode](</docs/en/headless>) with the `-p` flag, repeated blocks abort the session since there is no user to prompt. Repeated blocks usually mean the classifier is missing context about your infrastructure. Use `/feedback` to report false positives, or have an administrator [configure trusted infrastructure](</docs/en/auto-mode-config>). If you switch permission modes while a classifier check is pending, Claude Code discards a verdict the new mode wouldn’t have requested rather than applying it: you’re prompted for approval instead, or the action is auto-denied in `dontAsk` mode. +When auto mode can’t approve your session’s actions, what happens depends on the case: + + * **A blocked action** : Claude Code shows a notification and lists the action in `/permissions` under the **Recently denied** tab, where you can press `r` to retry it with a manual approval. When the classifier produces [no verdict on the action](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>), because a safety check separate from auto mode refused the classifier’s own request or its response didn’t parse, Claude Code denies the action without the notification or the **Recently denied** entry. + * **Repeated blocks** : if the classifier blocks an action 3 times in a row or 20 times total, auto mode pauses and Claude Code resumes prompting. Approving the prompted action resumes auto mode. These thresholds are not configurable. Any allowed action resets the consecutive counter, while the total counter persists for the session and resets only when its own limit triggers a fallback. Claude Code doesn’t count a denial toward either threshold when [a safety check separate from auto mode refuses the classifier’s own request](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>); the linked entry covers how Claude Code handles those denials. + * **Sessions that can’t prompt** : a [non-interactive](</docs/en/headless>) `-p` run without a [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) has no prompt to fall back to. When repeated blocks reach a threshold, the action doesn’t run and Claude keeps working, in the main conversation and in its subagents alike. The same applies when a safety check separate from auto mode refuses the classifier’s request. Claude Code doesn’t stop the run in either case. + * **A mode switch during a check** : if you switch permission modes while a classifier check is pending, Claude Code discards a verdict the new mode wouldn’t have requested rather than applying it: you’re prompted for approval instead, or the action is auto-denied in `dontAsk` mode. + +Repeated blocks usually mean the classifier is missing context about your infrastructure. Use `/feedback` to report false positives, or have an administrator [configure trusted infrastructure](</docs/en/auto-mode-config>). How the classifier evaluates actions @@ -307,7 +314,7 @@ 1. Before a subagent starts, the delegated task description is evaluated, so a dangerous-looking task is blocked at spawn time. 2. While the subagent runs, each of its actions goes through the classifier with the same rules as the parent session, and any `permissionMode` in the subagent’s frontmatter is ignored. - 3. When the subagent finishes, the classifier reviews its full action history; if that return check flags a concern, a security warning is prepended to the subagent’s results. + 3. When the subagent finishes, the classifier reviews its full action history; if that return check flags a concern, a security warning is prepended to the subagent’s results. When a separate API safety check refuses the review request itself, Claude Code still returns the subagent’s results, prepended with a warning that the work is unreviewed and should be treated as untrusted. Step 1 requires Claude Code v2.1.178 or later. Earlier versions applied the classifier at steps 2 and 3, but did not evaluate the task description before the subagent started.
modified Configure permissions View current →
--- a/permissions.md +++ b/permissions.md @@ -109,7 +109,7 @@ `plan`| Planning mode| Claude explores and plans without editing your source files; file edits are never auto-approved and prompt through your `canUseTool` callback `auto`| Model-classified approvals| A model classifier approves or denies permission prompts. See [Auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) for availability -**Subagent inheritance:** Subagents inherit the parent session’s permission mode. An [`AgentDefinition`’s `permissionMode`](</docs/en/agent-sdk/typescript#agentdefinition>) can override it, except when the parent uses `bypassPermissions`, `acceptEdits`, or `auto`: those modes apply to every subagent and can’t be overridden per subagent.Subagents may have different system prompts and less constrained behavior than your main agent, so inheriting `bypassPermissions` grants them full, autonomous system access. Explicit `ask` rules, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and tools that require user interaction still force a prompt, as does the [`isolatePeerMachines`](</docs/en/settings#available-settings>) approval for cross-machine messages. +**Subagent inheritance:** Subagents inherit the parent session’s permission mode. An [`AgentDefinition`’s `permissionMode`](</docs/en/agent-sdk/typescript#agentdefinition>) can override it, except when the parent uses `bypassPermissions`, `acceptEdits`, or `auto`: those modes apply to every subagent and can’t be overridden per subagent. Claude Code also ignores a definition’s `permissionMode: "bypassPermissions"` when bypass mode is disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>), so that subagent runs with the parent session’s mode.Subagents may have different system prompts and less constrained behavior than your main agent, so inheriting `bypassPermissions` grants them full, autonomous system access. Explicit `ask` rules, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and tools that require user interaction still force a prompt, as does the [`isolatePeerMachines`](</docs/en/settings#available-settings>) approval for cross-machine messages. ###
modified Constrain plugin dependency versions View current →
--- a/plugin-dependencies.md +++ b/plugin-dependencies.md @@ -1,4 +1,4 @@ -A plugin can depend on other plugins by listing them in `plugin.json` or in its marketplace entry. By default, a dependency tracks the latest available version, so an upstream release can change the dependency under your plugin without warning. Version constraints let you hold a dependency at a tested version range until you choose to move. When you install a plugin that declares dependencies, Claude Code resolves and installs them automatically. If a dependency later goes missing, `/reload-plugins` and the background plugin auto-update reinstall it, provided its marketplace is already in your configured marketplaces. Re-running `claude plugin install` on the dependent plugin, or adding a marketplace with `claude plugin marketplace add`, also resolves any outstanding missing dependencies. Dependencies from a marketplace you have not added are left unresolved. This guide is for plugin authors who declare dependencies in `plugin.json` and for marketplace maintainers who tag releases. To install plugins that have dependencies, see [Discover and install plugins](</docs/en/discover-plugins>). For the full manifest schema, see the [Plugins reference](</docs/en/plugins-reference>). +A plugin can depend on other plugins by listing them in `plugin.json` or in its marketplace entry. By default, a dependency tracks the latest available version, so an upstream release can change the dependency under your plugin without warning. Version constraints let you hold a dependency at a tested version range until you choose to move. When you install a plugin that declares dependencies, Claude Code resolves and installs them automatically. If a dependency later goes missing, `/reload-plugins` and the background plugin auto-update reinstall it, provided its marketplace is already in your configured marketplaces. Re-running `claude plugin install` on the dependent plugin, or adding a marketplace with `claude plugin marketplace add`, also resolves any outstanding missing dependencies. Dependencies from a marketplace you have not added are left unresolved. This guide is for plugin authors who declare dependencies in `plugin.json` and for marketplace maintainers who tag releases. Dependencies here are other plugins; for the npm and Bun packages a plugin itself uses, see [Node.js package dependencies](</docs/en/plugins-reference#node-js-package-dependencies>). To install plugins that have dependencies, see [Discover and install plugins](</docs/en/discover-plugins>). For the full manifest schema, see the [Plugins reference](</docs/en/plugins-reference>). ## @@ -110,7 +110,7 @@ * With `--push`, a successful run ends with `Created tag secrets-vault--v2.1.0` and `Pushed to origin`, where the last line names the remote it pushed to. Without `--push`, the command prints the `git push` command to run instead. * `--dry-run` prints what would be tagged without creating it. -Running `git tag secrets-vault--v2.1.0` directly is equivalent if you keep `plugin.json` and the marketplace entry in sync yourself. The plugin name prefix lets one marketplace repository host multiple plugins with independent version lines. The `--v` separator is parsed as a prefix match on the full plugin name, so plugin names that contain hyphens are handled correctly. When you install a plugin that declares `{ "name": "secrets-vault", "version": "~2.1.0" }`, Claude Code lists the tags on the repository that hosts `secrets-vault`, filters to those starting with `secrets-vault--v`, and fetches the highest version satisfying `~2.1.0`. If no tag on the plugin’s own repository satisfies the range, the install fails with `Dependency "secrets-vault" has no git tag satisfying ~2.1.0`. For a relative-path plugin with no matching tag, Claude Code installs the marketplace’s current copy instead and checks the constraint when the plugin loads. For a plugin the marketplace references by a relative path, a marketplace added as a local folder path resolves tags the same way when the folder is a git repository. This requires Claude Code v2.1.196 or later. In two cases Claude Code installs the dependency from the folder’s current contents instead: +Running `git tag secrets-vault--v2.1.0` directly is equivalent if you keep `plugin.json` and the marketplace entry in sync yourself. The plugin name prefix lets one marketplace repository host multiple plugins with independent version lines. The `--v` separator is parsed as a prefix match on the full plugin name, so plugin names that contain hyphens are handled correctly. When you install a plugin that declares `{ "name": "secrets-vault", "version": "~2.1.0" }`, Claude Code lists the tags on the repository that hosts `secrets-vault`, filters to those starting with `secrets-vault--v`, and fetches the highest version satisfying `~2.1.0`. If no tag on the plugin’s own repository satisfies the range, the install fails with `Dependency "secrets-vault@acme-tools" has no git tag satisfying ~2.1.0`, which names the dependency together with its marketplace. For a relative-path plugin with no matching tag, Claude Code installs the marketplace’s current copy instead and checks the constraint when the plugin loads. For a plugin the marketplace references by a relative path, a marketplace added as a local folder path resolves tags the same way when the folder is a git repository. This requires Claude Code v2.1.196 or later. In two cases Claude Code installs the dependency from the folder’s current contents instead: * Earlier versions don’t read tags from a local-folder marketplace, so a constrained dependency loads only if that copy satisfies the range. * A local folder that isn’t a git repository has no tags, regardless of version.
modified Create and distribute a plugin marketplace View current →
--- a/plugin-marketplaces.md +++ b/plugin-marketplaces.md @@ -258,7 +258,7 @@ Plugin sources -Plugin sources tell Claude Code where to fetch each individual plugin listed in your marketplace. These are set in the `source` field of each plugin entry in `marketplace.json`. After Claude Code clones or downloads a plugin to the local machine, it copies the plugin into the local versioned plugin cache at `~/.claude/plugins/cache`. +Plugin sources tell Claude Code where to fetch each individual plugin listed in your marketplace. These are set in the `source` field of each plugin entry in `marketplace.json`. After Claude Code clones or downloads a plugin to the local machine, it copies the plugin into the local versioned plugin cache at `~/.claude/plugins/cache`. Claude Code also [installs the plugin’s eligible Node.js package dependencies](</docs/en/plugins-reference#node-js-package-dependencies>) into the cached copy. Source| Type| Fields| Notes ---|---|---|--- @@ -728,7 +728,7 @@ ---|--- Undefined (default)| No restrictions. Users can add any marketplace Empty array `[]`| Complete lockdown. Blocks every marketplace source, including the official Anthropic marketplace -List of sources| Users can only add marketplaces that match the allowlist exactly +List of sources| Allowlist enforced. Users can add only marketplaces that match an entry #### @@ -742,7 +742,7 @@ "strictKnownMarketplaces": [] } -Allow only the official Anthropic marketplace. Matching is exact, so this entry doesn’t cover `ref` or `path` variants of the same repository: +Allow only the official Anthropic marketplace. Matching for a single-repository entry is exact, so this entry doesn’t cover `ref` or `path` variants of the same repository: { "strictKnownMarketplaces": [ @@ -778,6 +778,17 @@ ] } +Allow every marketplace repository under a GitHub organization with an [owner-wildcard](</docs/en/settings#owner-wildcards>) entry. Owner wildcards require Claude Code v2.1.223 or later. + + { + "strictKnownMarketplaces": [ + { + "source": "github", + "repo": "acme-corp/*" + } + ] + } + Allow all marketplaces from an internal git server using regex pattern matching on the host. This is the recommended approach for [GitHub Enterprise Server](</docs/en/github-enterprise-server#plugin-marketplaces-on-ghes>) or self-hosted GitLab instances: { @@ -810,9 +821,9 @@ How restrictions work -Restrictions are checked before any network or filesystem operation. The check runs on marketplace add and on plugin install, update, refresh, and auto-update. If a marketplace was added before the policy was configured and its source no longer matches the allowlist, Claude Code refuses to install or update plugins from it. The same enforcement applies to `blockedMarketplaces`. The allowlist uses exact matching for most source types. For a marketplace to be allowed, all specified fields must match exactly: - - * For GitHub sources: `repo` is required, and `ref` and `path` must each match exactly or be absent from both the marketplace source and the allowlist entry +Restrictions are checked before any network or filesystem operation. The check runs on marketplace add and on plugin install, update, refresh, and auto-update. If a marketplace was added before the policy was configured and its source no longer matches the allowlist, Claude Code refuses to install or update plugins from it. The same enforcement applies to `blockedMarketplaces`. To block every marketplace repository under a GitHub owner, use the owner-wildcard form in a `blockedMarketplaces` entry: `{ "source": "github", "repo": "untrusted-org/*" }`. Requires Claude Code v2.1.223 or later. For the matching rules, which differ between the blocklist and the allowlist, see [Owner wildcards](</docs/en/settings#owner-wildcards>). The allowlist uses exact matching for most source types, apart from owner-wildcard `github` entries. For a marketplace to be allowed, all specified fields must match: + + * For GitHub sources: `repo` is required, either naming one repository or using the owner-wildcard form `owner/*` to cover every repository under that owner. For how wildcard entries match, including the case rules, see [Owner wildcards](</docs/en/settings#owner-wildcards>). For single-repository entries, `ref` must match exactly or be absent from both the marketplace source and the allowlist entry, and the same rule applies to `path` * For URL sources: the full URL must match exactly * 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
modified Plugins reference View current →
--- a/plugins-reference.md +++ b/plugins-reference.md @@ -81,7 +81,7 @@ `UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion `PreToolUse`| Before a tool call executes. Can block it `PermissionRequest`| When a tool call needs a permission decision -`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call +`PermissionDenied`| When auto mode denies a tool call, including denials without a classifier verdict. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry the denied tool call. Claude Code ignores `retry` when the classifier produced no verdict `PostToolUse`| After a tool call succeeds `PostToolUseFailure`| After a tool call fails `PostToolBatch`| After a full batch of parallel tool calls resolves, before the next model call @@ -92,7 +92,7 @@ `TaskCreated`| When a task is being created via `TaskCreate` `TaskCompleted`| When a task is being marked as completed `Stop`| When Claude finishes responding -`StopFailure`| When the turn ends due to an API error. Output and exit code are ignored +`StopFailure`| When the turn ends due to an API error `TeammateIdle`| When an [agent team](</docs/en/agent-teams>) teammate is about to go idle `InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session `ConfigChange`| When a configuration file changes during a session @@ -201,7 +201,7 @@ Field| Description ---|--- `args`| Command-line arguments for the LSP server -`transport`| Communication transport: `stdio` (default) or `socket` +`transport`| Communication transport: `stdio` (default) or `socket`. Claude Code accepts `socket` but runs every server over stdio, so the stdout protocol rules apply to all servers `env`| Environment variables to set when starting the server `initializationOptions`| Options passed to the server during initialization `settings`| Settings passed via `workspace/didChangeConfiguration` @@ -212,7 +212,7 @@ `maxRestarts`| Maximum number of restart attempts before giving up `diagnostics`| Whether to push diagnostics into Claude’s context after edits (default `true`). Set to `false` to keep code navigation but suppress automatic diagnostic injection. -`restartOnCrash` and `shutdownTimeout` require Claude Code v2.1.205 or later. Before v2.1.205, the config schema accepted both options but setting either one caused Claude Code to skip that LSP server entirely at startup, with the reason visible only in `claude --debug` output. **Multiple servers for the same extension** : when more than one enabled LSP server declares the same file extension in `extensionToLanguage`, whether the servers come from one plugin or from different plugins, the first server registered handles files with that extension and the others never start. The `/plugin` interface shows a warning naming the plugin whose server is active. **Servers that fail to initialize** : Claude Code skips a server whose configuration is invalid, for example one missing `command` or `extensionToLanguage`, and the other configured servers still start. Run `claude --debug` to see why a server was skipped. A skipped server doesn’t claim its file extensions, so another valid server that declares the same extension, from the same or a different plugin, still handles those files. +`restartOnCrash` and `shutdownTimeout` require Claude Code v2.1.205 or later. Before v2.1.205, the config schema accepted both options but setting either one caused Claude Code to skip that LSP server entirely at startup, with the reason visible only in `claude --debug` output. **Multiple servers for the same extension** : when more than one enabled LSP server declares the same file extension in `extensionToLanguage`, whether the servers come from one plugin or from different plugins, the first server registered handles files with that extension and the others never start. The `/plugin` interface shows a warning naming the plugin whose server is active. **Servers that fail to initialize** : Claude Code skips a server whose configuration is invalid, for example one missing `command` or `extensionToLanguage`, and the other configured servers still start. Run `claude --debug` to see why a server was skipped. A skipped server doesn’t claim its file extensions, so another valid server that declares the same extension, from the same or a different plugin, still handles those files. **Send log output to stderr, not stdout** : Claude Code reads a server’s stdout as protocol messages only, and accepts message headers up to 64 KiB and a message body up to 32 MiB. Claude Code disconnects a server that exceeds either limit or writes non-protocol output to stdout, and counts the disconnect as a crash for `restartOnCrash` and `maxRestarts`. When you run with `--debug`, Claude Code writes an error naming the cause to the debug log. **You must install the language server binary separately.** LSP plugins configure how Claude Code connects to a language server, but they don’t include the server itself. If you see `Executable not found in $PATH` in the `/plugin` Errors tab, install the required binary for your language. @@ -651,7 +651,7 @@ } } -`${CLAUDE_PLUGIN_ROOT}` changes when the plugin updates. The previous version’s directory remains on disk for about two weeks after an update before cleanup, but treat it as ephemeral and don’t write state there. When a plugin updates mid-session, hook commands, monitors, MCP servers, and LSP servers keep using the previous version’s path. Run `/reload-plugins` to switch hooks, MCP servers, and LSP servers to the new path; monitors require a session restart. MCP servers can also call the `roots/list` request to read the session’s working directories at runtime. See [what `roots/list` returns and when Claude Code notifies the server of changes](</docs/en/mcp#option-3-add-a-local-stdio-server>). +`${CLAUDE_PLUGIN_ROOT}` changes when the plugin updates. The previous version’s directory remains on disk for a grace period after an update, but treat it as ephemeral and don’t write state there. See plugin caching for cleanup semantics. When a plugin updates mid-session, hook commands, monitors, MCP servers, and LSP servers keep using the previous version’s path. Run `/reload-plugins` to switch hooks, MCP servers, and LSP servers to the new path; monitors require a session restart. MCP servers can also call the `roots/list` request to read the session’s working directories at runtime. See [what `roots/list` returns and when Claude Code notifies the server of changes](</docs/en/mcp#option-3-add-a-local-stdio-server>). #### @@ -659,7 +659,7 @@ Persistent data directory -The `${CLAUDE_PLUGIN_DATA}` directory resolves to `~/.claude/plugins/data/{id}/`, where `{id}` is the plugin identifier with characters outside `a-z`, `A-Z`, `0-9`, `_`, and `-` replaced by `-`. For a plugin installed as `formatter@my-marketplace`, the directory is `~/.claude/plugins/data/formatter-my-marketplace/`. A common use is installing language dependencies once and reusing them across sessions and plugin updates. Because the data directory outlives any single plugin version, a check for directory existence alone cannot detect when an update changes the plugin’s dependency manifest. The recommended pattern compares the bundled manifest against a copy in the data directory and reinstalls when they differ. This `SessionStart` hook installs `node_modules` on the first run and again whenever a plugin update includes a changed `package.json`: +The `${CLAUDE_PLUGIN_DATA}` directory resolves to `~/.claude/plugins/data/{id}/`, where `{id}` is the plugin identifier with characters outside `a-z`, `A-Z`, `0-9`, `_`, and `-` replaced by `-`. For a plugin installed as `formatter@my-marketplace`, the directory is `~/.claude/plugins/data/formatter-my-marketplace/`. A common use is installing language dependencies once and reusing them across sessions and plugin updates. Use it for Python dependencies, dependencies locked with Yarn or pnpm, and packages whose lifecycle scripts must run. For a marketplace-installed plugin, you may not need it at all: Claude Code installs eligible Node.js package dependencies automatically when it caches the plugin. Because the data directory outlives any single plugin version, a check for directory existence alone cannot detect when an update changes the plugin’s dependency manifest. The recommended pattern compares the bundled manifest against a copy in the data directory and reinstalls when they differ. This `SessionStart` hook installs `node_modules` on the first run and again whenever a plugin update includes a changed `package.json`: { "hooks": { @@ -705,7 +705,28 @@ * Through `claude --plugin-dir` or `claude --plugin-url`, for the duration of a session. * Through a marketplace, installed for future sessions. -For security and verification purposes, Claude Code copies _marketplace_ plugins to the user’s local **plugin cache** (`~/.claude/plugins/cache`) rather than using them in-place. Each installed version is a separate directory in the cache. When you update or uninstall a plugin, the previous version directory is marked as orphaned and removed automatically 14 days later. The grace period lets concurrent Claude Code sessions that already loaded the old version keep running without errors. Claude’s Glob and Grep tools skip orphaned version directories during searches, so file results don’t include outdated plugin code. +For security and verification purposes, Claude Code copies _marketplace_ plugins to the user’s local **plugin cache** (`~/.claude/plugins/cache`) rather than using them in-place. Each installed version is a separate directory in the cache, grouped by marketplace and plugin and named for the resolved version, with its own copy of the plugin’s files and Node.js package dependencies. A dependency resolved from a [release tag](</docs/en/plugin-dependencies#tag-plugin-releases-for-version-resolution>) gets a directory name with a commit-SHA suffix. When you update or uninstall a plugin, Claude Code marks the previous version directory as orphaned and removes it in a background sweep roughly 14 days later. The grace period lets concurrent Claude Code sessions that already loaded the old version keep running without errors. Claude Code runs the sweep only while at least one plugin is installed; after you uninstall your last plugin, orphaned directories stay on disk until you install a plugin again. Claude’s Glob and Grep tools skip orphaned version directories during searches, so file results don’t include outdated plugin code. + +### + +​ + +Node.js package dependencies + +When Claude Code copies a plugin into the cache, it also installs the plugin’s Node.js package dependencies there, so the plugin’s hooks and MCP servers can load them. This section covers the npm and Bun packages a plugin declares in its own `package.json`. For plugins that depend on other plugins, see [plugin dependency versions](</docs/en/plugin-dependencies>). Claude Code runs the install inside the cached version directory each time it creates one: when you install a plugin, when Claude Code updates a plugin to a new version, and at session start when an enabled plugin isn’t cached yet, such as on a new machine. The install runs only when the plugin’s root directory contains both a `package.json` and a supported lockfile: + +Lockfile| Command +---|--- +`bun.lock` or `bun.lockb`| `bun install --frozen-lockfile --ignore-scripts` +`npm-shrinkwrap.json` or `package-lock.json`| `npm ci --ignore-scripts` + +If a plugin contains more than one of these lockfiles, Claude Code uses the first match, checking in order: `bun.lock`, `bun.lockb`, `npm-shrinkwrap.json`, `package-lock.json`. Claude Code skips `yarn.lock` and `pnpm-lock.yaml` because Yarn and pnpm support resolution-time configuration hooks that bypass `--ignore-scripts`. Ship an npm lockfile for the widest reach. Claude Code runs the matched lockfile’s package manager from the user’s PATH and doesn’t fall back to the other lockfile if it’s missing. For a plugin distributed through an npm source, use `npm-shrinkwrap.json`; npm excludes `package-lock.json` from published packages. Claude Code constrains this dependency install so that no code from the plugin or its packages executes during it, and bounds how long it can run: + + * **Frozen resolution:** Bun and npm install exactly what the lockfile pins, and fail rather than re-resolve versions when `package.json` and the lockfile disagree. + * **No lifecycle scripts:** `--ignore-scripts` keeps `preinstall`, `install`, and `postinstall` scripts from running, so dependencies that build native modules in those scripts download but don’t compile during this install. + * **60-second timeout:** Claude Code stops an install that runs longer and treats it as failed. + +Fetching an npm-source plugin itself runs `npm install` with lifecycle scripts enabled, before this dependency install runs. A failed or skipped install never blocks the plugin. When the install fails, or Claude Code skips a yarn or pnpm lockfile, it records the reason as a warning in debug output. A plugin with a `package.json` and no lockfile is skipped without a log entry. A timed-out install can leave a partial `node_modules` tree in the cached copy. You can’t turn the automatic install off; no setting or environment variable disables it. In restricted networks, see the [network access requirements](</docs/en/network-config#network-access-requirements>) for the hosts to allow. For dependencies the automatic install can’t provide, such as packages that need their lifecycle scripts to build, Python dependencies, or a plugin locked with Yarn or pnpm, install them from a hook into the persistent data directory. ### @@ -810,7 +831,7 @@ **LSP servers**| `.lsp.json`| Language server configurations **Monitors**| `monitors/monitors.json`| Background monitor configurations **Executables**| `bin/`| Executables added to the Bash tool’s `PATH`. Files here are invokable as bare commands in any Bash tool call while the plugin is enabled -**Settings**| `settings.json`| Default configuration applied when the plugin is enabled. Only the [`agent`](</docs/en/sub-agents>) and [`subagentStatusLine`](</docs/en/statusline#subagent-status-lines>) keys are currently supported +**Settings**| `settings.json`| Default configuration applied when the plugin is enabled. Only the [`agent`](</docs/en/sub-agents>) and [`subagentStatusLine`](</docs/en/statusline#subagent-status-lines>) keys are supported * * *
modified Agent SDK reference - Python View current →
--- a/python.md +++ b/python.md @@ -1717,7 +1717,7 @@ * `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes. * `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are `interrupt()` and a permission callback returning `PermissionResultDeny` with `interrupt=True`. `None` on CLI versions that predate the field, on results that bypassed the query loop such as local slash commands, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK’s [`SDKResultMessage.terminal_reason`](</docs/en/agent-sdk/typescript#sdkresultmessage>), which lists the full set of values. -The `usage` dict contains the following keys when present: +The `usage` dict covers the main agent loop only and excludes subagent and other nested or auxiliary model calls. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), the values are per-turn. Prefer `model_usage` for token and cost accounting. The `usage` dict contains the following keys when present: Key| Type| Description ---|---|--- @@ -1726,7 +1726,7 @@ `cache_creation_input_tokens`| `int`| Tokens used to create new cache entries. `cache_read_input_tokens`| `int`| Tokens read from existing cache entries. -The `model_usage` dict maps model names to per-model usage. Each value is a `ModelUsage` TypedDict whose keys use camelCase, because the value is passed through unmodified from the underlying CLI process. Import via `from claude_agent_sdk.types import ModelUsage`. The keys are: +The `model_usage` dict maps model names to per-model usage. It covers every model call made through the query pipeline: 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 from `model_usage`. Treat `model_usage` as an estimate, not a billing statement. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), `model_usage` and `total_cost_usd` 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. Each value in `model_usage` is a `ModelUsage` TypedDict, imported via `from claude_agent_sdk.types import ModelUsage`. Its keys use camelCase because the SDK passes the value through unmodified from the underlying CLI process, matching the TypeScript [`ModelUsage`](</docs/en/agent-sdk/typescript#modelusage>) type: Key| Type| Description ---|---|--- @@ -2613,7 +2613,7 @@ "modelsUsed": list[str] | None, # Models used in order, with consecutive repeats collapsed "totalToolUseCount": int, # Number of tool calls the agent made "totalDurationMs": int, # Execution duration in milliseconds - "totalTokens": int, # Total tokens used + "totalTokens": int, # Token count from the final API request, not the whole run "usage": { # Token usage statistics "input_tokens": int, "output_tokens": int,
modified Continue local sessions from any device with Remote Control View current →
Show diff (104 lines)
--- a/remote-control.md +++ b/remote-control.md @@ -2,10 +2,10 @@ Remote Control connects [claude.ai/code](<https://claude.ai/code>) or the Claude app for [iOS](<https://apps.apple.com/us/app/claude-by-anthropic/id6473753684>) and [Android](<https://play.google.com/store/apps/details?id=com.anthropic.claude>) to a Claude Code session running on your machine. Start a task at your desk, then pick it up from your phone on the couch or a browser on another computer. When you start a Remote Control session on your machine, Claude keeps running locally the entire time, so your code execution and filesystem access stay on your machine. With Remote Control you can: - * **Use your full local environment remotely** : your filesystem, [MCP servers](</docs/en/mcp>), tools, and project configuration all stay available, and typing `@` autocompletes file paths from your local project - * **Work from both surfaces at once** : the conversation and the progress of [subagents](</docs/en/sub-agents>) and [dynamic workflows](</docs/en/workflows>) stay in sync across all connected devices, so you can send messages from your terminal, browser, and phone interchangeably. Before v2.1.207, sessions hosted by the [Desktop app](</docs/en/desktop>) didn’t send subagent or workflow progress to connected devices. - * **Send images and files from your phone or browser** : when you add an attachment in the Claude app or at claude.ai/code, Claude Code downloads it to your machine and passes it to Claude as an `@` file reference, with or without a caption. Before v2.1.202, Claude Code could drop an attachment sent without a caption before it reached the session. - * **Survive interruptions** : if your laptop sleeps or your network drops, the session reconnects automatically when your machine comes back online. Claude Code queues status updates from subagents and workflows while the connection is rebuilding and delivers them once it recovers. Before v2.1.207, an update sent during a reconnection or credential refresh could be lost, so the connected device kept showing a finished task as running. + * **Use your full local environment remotely** : your filesystem, [MCP servers](</docs/en/mcp>), tools, and project configuration all stay available, and typing `@` autocompletes file paths from your local project. + * **Work from both surfaces at once** : the conversation and the progress of [subagents](</docs/en/sub-agents>) and [dynamic workflows](</docs/en/workflows>) stay in sync across all connected devices, so you can send messages from your terminal, browser, and phone interchangeably. + * **Send images and files from your phone or browser** : attach a photo or file in the Claude app or at claude.ai/code, with or without a caption. Claude sees attached photos directly as part of your message. Claude Code downloads other files to your machine and passes them to Claude as `@` file references. + * **Survive interruptions** : if your laptop sleeps or your network drops, Claude Code reconnects automatically when your machine comes back online. Claude Code queues status updates from subagents and workflows while the connection is rebuilding and delivers them once it recovers. Unlike [Claude Code on the web](</docs/en/claude-code-on-the-web>), which runs on cloud infrastructure, Remote Control sessions run directly on your machine and interact with your local filesystem. The web and mobile interfaces are a window into that local session. This page covers setup, how to start and connect to sessions, and how Remote Control compares to Claude Code on the web. @@ -95,7 +95,7 @@ Check connection status -In an interactive terminal session, a `/rc active` indicator sits in the footer below the input box while the connection is up, and is hidden if the terminal is too narrow to fit it. The indicator text is a link to the session on claude.ai. Select it with the down arrow key and press Enter, or run `/remote-control` again, to open a status panel with the session URL and a QR code you can use to connect from another device. If the connection fails, a notification appears with the failure reason and the indicator disappears from the footer. Run `/remote-control` again to retry. +In an interactive terminal session, a `/rc active` indicator sits in the footer below the input box while the connection is up, and is hidden if the terminal is too narrow to fit it. The indicator text is a link to the session on claude.ai. Select it with the down arrow key and press Enter, or run `/remote-control` again, to open a status panel with the session URL and a QR code you can use to connect from another device. The status panel also offers a disconnect option. Select it to turn Remote Control off; your local session keeps running in the terminal. If the connection fails, Claude Code shows a notification with the failure reason, and the indicator changes to a failure state that stays in the footer. Select the indicator and press Enter to review the details, or run `/remote-control` to retry. ### @@ -103,9 +103,9 @@ Session URL reminders -While Remote Control is connected, Claude Code reminds you of the session URL at the moments when switching to your phone or browser helps most, so you don’t have to dig the link out of `/remote-control`. Requires Claude Code v2.1.208 or later. A reminder appears above the prompt box at either of these moments: - - * **Long turn** : when a turn runs longer than a server-tuned threshold, a **Still working** notification with a **Check in from your phone** link appears, so you can follow the turn from your phone or browser instead of waiting at the terminal. Claude Code removes it when the turn ends. +While Remote Control is connected, Claude Code reminds you of the session URL when switching to your phone or browser helps most, so you don’t have to find the link in `/remote-control`. A reminder appears above the prompt box at either of these moments: + + * **Long turn** : when a turn runs longer than a server-tuned threshold, Claude Code shows a **Still working** notification with a **Check in from your phone** link, so you can follow the turn from your phone or browser instead of waiting at the terminal. Claude Code removes it when the turn ends. * **Repeated permission prompts** : after you answer several [permission prompts](</docs/en/permissions>) in a session, an **Approve tool calls from your phone** notification shows the session URL. Claude Code removes it when your next turn starts. The reminders can appear in any connected session, including ones where Remote Control connects automatically. They don’t appear every time these conditions occur, and each one appears only a few times in total across sessions. You can’t configure or turn them off; each clears on its own. @@ -129,7 +129,7 @@ 3. The last meaningful message in existing conversation history 4. An auto-generated name like `myhost-graceful-unicorn`, where `myhost` is your machine’s hostname or the prefix you set with `--remote-control-session-name-prefix` -If you didn’t set an explicit name, Claude Code updates the title to reflect your prompt once you send one. Claude Code matches auto-generated titles to the language of your conversation, or to the [`language`](</docs/en/settings#available-settings>) setting if one is configured; the language matching requires Claude Code v2.1.176 or later. When you rename a session from claude.ai or the Claude app, Claude Code also updates the local title shown in `claude --resume`. Claude Code applies the same rename to the session name shown on the prompt bar, and in the `claude agents` listing when the session [runs in the background](</docs/en/agent-view>). Before v2.1.221, renaming from the session list at claude.ai or in the Claude app updated only the title, and the CLI kept its previous session name; `/rename`, which runs in the CLI itself, set the name on any version. If the environment already has an active session, you’ll be asked whether to continue it or start a new one. If you don’t have the Claude app yet, use the `/mobile` command inside Claude Code to display a download QR code for [iOS](<https://apps.apple.com/us/app/claude-by-anthropic/id6473753684>) or [Android](<https://play.google.com/store/apps/details?id=com.anthropic.claude>). +If you didn’t set an explicit name, Claude Code updates the title to reflect your prompt once you send one. Claude Code matches auto-generated titles to the language of your conversation, or to the [`language`](</docs/en/settings#available-settings>) setting if one is configured; the language matching requires Claude Code v2.1.176 or later. When you rename a session from claude.ai or the Claude app, Claude Code also updates the local title shown in `claude --resume`. Claude Code applies the same rename to the session name shown on the prompt bar, and in the `claude agents` listing when the session [runs in the background](</docs/en/agent-view>). Before v2.1.221, renaming from the session list at claude.ai or in the Claude app updated only the title, and the CLI kept its previous session name; `/rename`, which runs in the CLI itself, set the name on any version. When Claude Code stops using a session, it archives the session instead of leaving it in the session list. This happens, for example, when [compaction](</docs/en/context-window#what-survives-compaction>) rewrites the conversation while Remote Control is disconnected, or when you switch to a different conversation with `/resume`. The session stays available when you [filter for archived sessions](</docs/en/claude-code-on-the-web#archive-sessions>). If the environment already has an active session, you’ll be asked whether to continue it or start a new one. If you don’t have the Claude app yet, use the `/mobile` command inside Claude Code to display a download QR code for [iOS](<https://apps.apple.com/us/app/claude-by-anthropic/id6473753684>) or [Android](<https://play.google.com/store/apps/details?id=com.anthropic.claude>). ### @@ -156,7 +156,7 @@ Connection and security -Your local Claude Code session makes outbound HTTPS requests only and never opens inbound ports on your machine. When you start Remote Control, it registers with the Anthropic API and polls for work. When you connect from another device, the server routes messages between the web or mobile client and your local session over a streaming connection. All traffic travels through the Anthropic API over TLS, the same transport security as any Claude Code session. The connection uses multiple short-lived credentials, each scoped to a single purpose and expiring independently. While Remote Control is connected, the session transcript, including your messages, Claude’s responses, and tool activity, is stored on Anthropic servers. The stored transcript keeps the conversation in sync across your devices and lets the session reconnect after a network drop. Execution and filesystem access stay on your machine, and stored transcripts are retained under the [Data usage](</docs/en/data-usage>) policy. With [cross-session messaging](</docs/en/cross-session-messaging>), the Remote Control connection also carries messages between your own Claude Code sessions on different machines, and messages arriving from your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions, traveling through Anthropic servers like the rest of Remote Control traffic. [Message sessions on other machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>) covers the cross-machine delivery rules and the `isolatePeerMachines` approval requirement. [Control inbound messages](</docs/en/cross-session-messaging#control-inbound-messages>) covers the inbound controls. Cross-session messaging requires Claude Code v2.1.224 or later. To turn Remote Control off entirely, use the [`disableRemoteControl`](</docs/en/settings#available-settings>) setting. Organizations with compliance requirements such as Zero Data Retention can’t enable Remote Control. +Your local Claude Code session makes outbound HTTPS requests only and never opens inbound ports on your machine. When you start Remote Control, it registers with the Anthropic API and polls for work. When you connect from another device, the server routes messages between the web or mobile client and your local session over a streaming connection. All traffic travels through the Anthropic API over TLS, the same transport security as any Claude Code session. The connection uses multiple short-lived credentials, each scoped to a single purpose and expiring independently. While Remote Control is connected, the session transcript, including your messages, Claude’s responses, and tool activity, is stored on Anthropic servers. The stored transcript keeps the conversation in sync across your devices and lets the session reconnect after a network drop. Execution and filesystem access stay on your machine, and stored transcripts are retained under the [Data usage](</docs/en/data-usage>) policy. Context changes stay in sync too. While Claude Code [compacts the conversation](</docs/en/context-window#what-survives-compaction>), connected devices show compaction progress and, once compaction finishes, where the conversation was compacted. When you run `/clear`, the conversation resets on connected devices. With [cross-session messaging](</docs/en/cross-session-messaging>), the Remote Control connection also carries messages between your own Claude Code sessions on different machines, and messages arriving from your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions. These messages travel through Anthropic servers like the rest of Remote Control traffic. [Message sessions on other machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>) covers the cross-machine delivery rules and the `isolatePeerMachines` approval requirement, and [Control inbound messages](</docs/en/cross-session-messaging#control-inbound-messages>) covers the inbound controls. Cross-session messaging requires Claude Code v2.1.224 or later. To turn Remote Control off entirely, use the [`disableRemoteControl`](</docs/en/settings#available-settings>) setting. Organizations with compliance requirements such as Zero Data Retention can’t enable Remote Control. ## @@ -278,7 +278,7 @@ * **One remote session per interactive process** : outside of server mode, each Claude Code instance supports one remote session at a time. Use server mode to run multiple concurrent sessions from a single process. * **Local process must keep running** : Remote Control runs as a local process. If you close the terminal, quit VS Code, or otherwise stop the `claude` process, the session ends. To keep a session running on a remote machine after you disconnect from SSH, start it inside `tmux` or `screen`. * **Extended network outage** : if your machine is awake but unable to reach the network for more than roughly 10 minutes, the session times out and the process exits. Run `claude remote-control` again to start a new session. - * **Forwarded dialogs expire** : Claude Code keeps permission prompts and `AskUserQuestion` questions open until you answer them. When Claude Code forwards another kind of dialog to the remote session, it waits five minutes by default, then closes the dialog and continues with the dialog’s no-action default. Set [`dialogExpiry`](</docs/en/settings#available-settings>) to adjust or disable the deadline. Requires Claude Code v2.1.224 or later. + * **Forwarded dialogs expire** : Claude Code keeps permission prompts and `AskUserQuestion` questions open until you answer them. When Claude Code forwards another kind of dialog to the remote session, such as the model-choice prompt shown after a safety refusal, it waits five minutes by default, then closes the dialog and continues with the dialog’s no-action default. Set [`dialogExpiry`](</docs/en/settings#available-settings>) to adjust or disable the deadline. Requires Claude Code v2.1.224 or later. The approval dialog for a held cross-session message uses the same deadline. [The held-message expiry rules](</docs/en/cross-session-messaging#control-inbound-messages>) cover the cases where Claude Code keeps the dialog open past it. * **Some commands are local-only** : commands that only run in the terminal interface, such as `/plugin` or `/resume`, work only from the local CLI, whether or not you pass an argument. The following work from mobile and web: * Text-output commands: `/compact`, `/clear`, `/context`, `/usage`, `/exit`, `/usage-credits` (prints the billing URL instead of opening a browser), `/recap`, `/reload-plugins` * `/model`, `/effort`, `/fast`, `/color`, and `/rename`: pass the value as an argument, for example `/model sonnet` or `/effort high`. From mobile and web, `/model` and `/effort` take the argument in place of the terminal picker or slider. @@ -384,13 +384,36 @@ * Network or proxy issue: a firewall or proxy may be blocking the outbound HTTPS request. Remote Control requires access to the Anthropic API on port 443. * Session creation failed: if you also see `Session creation failed — see debug log`, the failure happened earlier in setup. Check that your subscription is active. +A stale login token doesn’t cause this error. When the Anthropic API rejects the saved token, for example because another Claude Code process already refreshed it, Claude Code refreshes the token and retries on its own. Before v2.1.224, a stale token failed Remote Control startup with this message, so sessions set to connect automatically could fail intermittently at launch. + ### ​ ”Couldn’t reconnect to your Remote Control session” -When you resume a conversation with `claude --resume` or `claude --continue`, Claude Code reconnects to the Remote Control session recorded in that conversation. This message means the reconnection failed for a reason that may be temporary, such as a network interruption or a server error, so Claude Code can’t confirm whether the remote session still exists. When the server confirms the previous session no longer exists, Claude Code creates a new Remote Control session without showing this message. Your local session keeps running without Remote Control. Run `/remote-control` to retry the connection, or start Claude Code without `--resume` to create a new Remote Control session. Before v2.1.200, a reconnection failure created a new Remote Control session instead of showing this message, which left extra sessions in the session list at claude.ai/code. +When you resume a conversation with `claude --resume` or `claude --continue`, Claude Code reconnects to the Remote Control session recorded in that conversation. This message means the reconnection failed for a reason that may be temporary, such as a network interruption or a server error, so Claude Code can’t confirm whether the remote session still exists. Your local session keeps running without Remote Control. Run `/remote-control` to retry the connection, or start a new session with `claude --remote-control` to create a new Remote Control session. Resuming can also end in two other ways: + + * **The server reports that the recorded session no longer exists** : Claude Code shows `Remote Control could not resume the previous session under the current login` instead of this message, doesn’t create a replacement session, and removes the reconnection record from the conversation. + * **Remote Control was turned off before you resumed** : Claude Code keeps the reconnection record only while Remote Control stays on. Turning it off from the CLI’s status panel, the VS Code extension, or a host built on the [Agent SDK](</docs/en/agent-sdk/overview>) removes the record, so resuming doesn’t reconnect Remote Control. + +Earlier versions created a new Remote Control session instead of showing a message: before v2.1.200 on any reconnection failure, and through v2.1.226 when the server reported the session gone. + +### + +​ + +“Remote Control could not resume the previous session under the current login” + +Claude Code tried to reconnect to a previous Remote Control session and stopped: it couldn’t confirm that the session is still available to the account you’re now signed in with, for example because you signed in to a different account or the server reported the session gone. You can see this message after resuming a conversation with `claude --resume` or `claude --continue`, or after Claude Code reconnects on its own following a disconnect. Rather than start a fresh remote session, which by default would upload the local conversation under an account that may not own it, Claude Code leaves the session running locally without Remote Control. Run `/remote-control` to start a fresh Remote Control session under the current login. The related message `Remote Control could not verify the signed-in account — run /remote-control to reconnect` appears when the signed-in account changed or couldn’t be read between Claude Code validating it and reconnecting, and has the same fix. The automatic reconnection is part of disconnect recovery. When a [Remote Control disconnect message](</docs/en/errors#remote-control-couldnt-refresh-your-login>) says to run `/login` to restore Remote Control, Claude Code watches for a new sign-in and reconnects to the previous remote session on its own. Any other disconnect listed in that entry needs a manual `/remote-control`. Both messages were added in v2.1.225. + +### + +​ + +”Remote Control got an unexpected server response” + +The Remote Control server accepted a request but replied in a form this version of Claude Code couldn’t read, while creating the remote session or fetching its credentials. Retrying on the same version fails the same way. Run `claude update`, then run `/remote-control` to reconnect. This message was added in v2.1.225. ###
modified Automate work with routines View current →
--- a/routines.md +++ b/routines.md @@ -40,7 +40,7 @@ Name the routine and write the prompt -Give the routine a descriptive name and write the prompt Claude runs each time. The prompt is the most important part: the routine runs autonomously, so the prompt must be self-contained and explicit about what to do and what success looks like.When a trigger fires, the session receives the routine’s saved prompt as its assigned task and carries it out, rather than treating it as untrusted content that arrived mid-conversation. The trigger attests only that the prompt was stored ahead of time by an authorized session on your account, so the fired prompt is not live user input and can’t act as approval or consent for actions during the run. Content the session fetches during the run keeps its normal handling. Before v2.1.214, the session received the same prompt framed as an untrusted background notification and could refuse to act on it.The prompt input includes a model selector. Claude uses the selected model on every run. +Give the routine a descriptive name and write the prompt Claude runs each time. The prompt is the most important part: the routine runs autonomously, so the prompt must be self-contained and explicit about what to do and what success looks like.When a trigger fires, the session receives the routine’s saved prompt as its assigned task and carries it out, rather than treating it as untrusted content that arrived mid-conversation. The trigger attests only that the prompt was stored ahead of time by an authorized session on your account, so the fired prompt is not live user input and can’t act as approval or consent for actions during the run. Content the session fetches during the run keeps its normal handling. Before v2.1.213, the session received the same prompt framed as an untrusted background notification and could refuse to act on it.The prompt input includes a model selector. Claude uses the selected model on every run. 3 @@ -96,7 +96,7 @@ Create from the CLI -Run `/schedule` in any session to create a scheduled routine conversationally. You can also pass a description directly, for a recurring routine like `/schedule daily PR review at 9am` or a one-off like `/schedule clean up feature flag in one week`. Claude walks through the same information the web form collects, then saves the routine to your account. The command is also available under the alias `/routines`. A successful start looks like a conversation: Claude asks follow-up questions about the schedule, repositories, and prompt before saving. If Claude instead replies that you need to authenticate or that it can’t connect to your remote claude.ai account, no routine was created; see Troubleshooting. `/schedule` in the CLI creates scheduled routines only. To add an API or GitHub trigger, edit the routine on the web at [claude.ai/code/routines](<https://claude.ai/code/routines>). The CLI also supports managing existing routines. Run `/schedule list` to see all routines, `/schedule update` to change one, or `/schedule run` to trigger it immediately. A routine with no schedule trigger, such as one started only by API calls or GitHub events, has no next run time, and the CLI shows none when Claude saves or updates it. Before v2.1.211, the CLI reported a next run time in the year 1 for these routines. +Run `/schedule` in any session to create a scheduled routine conversationally. You can also pass a description directly, for a recurring routine like `/schedule daily PR review at 9am` or a one-off like `/schedule clean up feature flag in one week`. Claude walks through the same information the web form collects, then saves the routine to your account. The command is also available under the alias `/routines`. A successful start looks like a conversation: Claude asks follow-up questions about the schedule, repositories, and prompt before saving. If Claude instead replies that you need to authenticate or that it can’t connect to your remote claude.ai account, no routine was created; see Troubleshooting. `/schedule` in the CLI creates scheduled routines. To add an API trigger, edit the routine on the web at [claude.ai/code/routines](<https://claude.ai/code/routines>). You can add a GitHub trigger from the web or from the CLI. The CLI path requires Claude Code v2.1.225 or later. A routine with no schedule trigger, such as one started only by API calls or GitHub events, has no next run time, and the CLI shows none when Claude saves or updates it. Before v2.1.211, the CLI reported a next run time in the year 1 for these routines. ## @@ -211,7 +211,10 @@ During the research preview, GitHub webhook events are subject to per-routine and per-account hourly caps. Events beyond the limit are dropped until the window resets. See your current limits at [claude.ai/code/routines](<https://claude.ai/code/routines>). -GitHub triggers are configured from the web UI only. +The Claude GitHub App must be installed on the repository you want to subscribe to, whichever surface you configure the trigger from. + + * Configure GitHub triggers from the web UI, which prompts you to install the app when it’s missing. Follow the steps below to configure one on the web. + * From the CLI, install the app from the [GitHub App page](<https://github.com/apps/claude>) first, then ask Claude to attach a GitHub trigger to an existing routine, for example `/schedule add a GitHub trigger to my nightly review for pull requests opened in acme/webapp`. The CLI path requires Claude Code v2.1.225 or later. When Claude adds the trigger, it replies with a link to the routine the trigger fires. 1 @@ -225,15 +228,9 @@ Scroll to the **Select a trigger** section, click **Add another trigger** , and choose **GitHub event**. +Running `/web-setup` in the CLI grants repository access for cloning, but it does not install the Claude GitHub App and does not enable webhook delivery. + 3 - -Install the Claude GitHub App - -The Claude GitHub App must be installed on the repository you want to subscribe to. The trigger setup prompts you to install it if it isn’t already. - -Running `/web-setup` in the CLI grants repository access for cloning, but it does not install the Claude GitHub App and does not enable webhook delivery. - -4 Configure the trigger @@ -312,6 +309,14 @@ ​ +Manage routines from the CLI + +The CLI supports managing existing routines. Run `/schedule list` to see all routines, `/schedule update` to change one, or `/schedule run` to trigger it immediately. You can also ask about a routine’s run history, for example `/schedule why did my nightly review do nothing this morning?`. Claude lists the routine’s recent runs with their status and a link to open each run on the web, and reads a run’s log to explain what happened, including tool errors, permission denials, and the final result. Requires Claude Code v2.1.227 or later. + +### + +​ + 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: @@ -388,13 +393,15 @@ `/schedule` returns “Unknown command” -The CLI hides `/schedule` when one of its requirements isn’t met: the command menu shows `No commands match "/schedule"` while you type, and submitting it returns `Unknown command: /schedule` in every case below except a Console API key with feature-flag fetching enabled. The cause is usually one of the following: - - * You are authenticated with a Console API key or a cloud provider such as Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. `/schedule` requires a claude.ai subscription login. With a Console API key, submitting `/schedule` instead shows `/schedule is available with Claude for Enterprise — ask your admin about migrating from API-key access`. With a cloud-provider login, you still see `Unknown command: /schedule`. If `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` is set in your shell, or `apiKeyHelper` is set in `settings.json`, remove it first, since these take precedence over a claude.ai login +The CLI hides `/schedule` when one of its requirements isn’t met: the command menu shows `No commands match "/schedule"` while you type, and submitting it returns `Unknown command: /schedule` in every case below except a Console API key or an Anthropic profile with feature-flag fetching enabled. The cause is usually one of the following: + + * You are authenticated with a Console API key, an [Anthropic profile or federation credential](</docs/en/authentication#anthropic-profiles-and-federation-credentials>), or a cloud provider such as Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. `/schedule` requires a claude.ai subscription login. With a Console API key or a profile, submitting `/schedule` instead shows `/schedule is available with Claude for Enterprise — ask your admin about migrating from API-key access`. With a cloud-provider login, you still see `Unknown command: /schedule`. If `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` is set in your shell, or `apiKeyHelper` is set in `settings.json`, remove it first, since these take precedence over a claude.ai login. A profile or federation credential takes precedence too, so switch that off as well * `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, or `DISABLE_GROWTHBOOK` is set in your shell environment or in the `env` block of a [`settings.json` file](</docs/en/settings#available-settings>). These disable feature-flag fetching, which `/schedule` depends on * You are inside a Claude Code on the web session. Manage routines from the [web UI](<https://claude.ai/code/routines>) instead - -You can always create and manage routines at [claude.ai/code/routines](<https://claude.ai/code/routines>) regardless of how the CLI is configured. + * Your organization’s policy disables [Claude Code on the web](</docs/en/claude-code-on-the-web>), which routines run on + * An Owner turned off routines for your Team or Enterprise organization. Before v2.1.227, the command still appeared in this case, and claude.ai rejected the routine when Claude tried to create or run it + +Unless your organization’s policy disables routines or Claude Code on the web, you can create and manage routines at [claude.ai/code/routines](<https://claude.ai/code/routines>) regardless of how the CLI is configured. ### @@ -408,9 +415,9 @@ ​ -”Routines are disabled by your organization’s policy” - -An Owner in your Team or Enterprise organization has likely turned off the **Routines** toggle at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>). This is a server-side organization setting, so it cannot be overridden from your local configuration. Ask an Owner to enable routines for your organization. +“Routines are disabled by your organization’s policy” + +An Owner in your Team or Enterprise organization has likely turned off the **Routines** toggle at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>). On Claude Code v2.1.227 or later, the same toggle also hides `/schedule` in the CLI. This is a server-side organization setting, so it cannot be overridden from your local configuration. Ask an Owner to enable routines for your organization. ##
modified Configure the sandboxed Bash tool View current →
Show diff (111 lines)
--- a/sandboxing.md +++ b/sandboxing.md @@ -93,16 +93,46 @@ Sandbox modes -Claude Code offers two sandbox modes: **Auto-allow mode** : when a command can be sandboxed, Claude Code runs it inside the sandbox and approves it automatically, without asking your permission. Commands that cannot be sandboxed, such as those needing network access to non-allowed hosts, fall back to the regular permission flow, where Claude Code checks your [permission rules](</docs/en/permissions>) and gates any command those rules do not already allow, with a prompt in default mode or the classifier in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Even in auto-allow mode, the following still apply: +Claude Code offers two sandbox modes. In both, the sandbox enforces the same filesystem and network restrictions; the difference is only in whether sandboxed commands are auto-approved or require explicit permission. + +#### + +​ + +Auto-allow mode + +When a command can be sandboxed, Claude Code runs it inside the sandbox and approves it automatically, without asking your permission. Commands that cannot be sandboxed, such as those needing network access to non-allowed hosts, fall back to the regular permission flow, where Claude Code checks your [permission rules](</docs/en/permissions>) and gates any command those rules do not already allow, with a prompt in default mode or the classifier in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Even in auto-allow mode, the following still apply: * Explicit [deny rules](</docs/en/permissions>) are always respected * `rm` or `rmdir` commands that target `/`, your home directory, or other critical system paths still trigger a permission prompt, or a classifier check in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>); the classifier routing requires Claude Code v2.1.218 or later * Content-scoped [ask rules](</docs/en/permissions>) like `Bash(git push *)` still force a prompt even for sandboxed commands * A bare `Bash` ask rule, or the equivalent `Bash(*)` form, is skipped for commands that run sandboxed; it still applies to commands that fall back to the regular permission flow. In [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>), the rule isn’t skipped: it prompts for sandboxed commands too, including read-only ones. Before v2.1.212, the skip applied in plan mode as well -**Regular permissions mode** : All Bash commands go through the regular permission flow, even when sandboxed. This provides more control but requires more approvals. In both modes, the sandbox enforces the same filesystem and network restrictions. The difference is only in whether sandboxed commands are auto-approved or require explicit permission. The session temp directory is writable inside the sandbox by default, alongside the working directory. Unless you disable filesystem isolation, Claude Code sets `$TMPDIR` to this directory for sandboxed commands, so tools that write temporary files work without extra configuration. Unsandboxed commands inherit your shell’s `$TMPDIR` unchanged, so while filesystem isolation is on, sandboxed and unsandboxed commands resolve `$TMPDIR` to different directories. To pass temporary files between the two, write them under the working directory instead. Some commands cannot run inside the sandbox at all, such as tools that are incompatible with it or that need a host you have not allowed. Rather than failing the task or requiring you to turn sandboxing off, Claude Code includes an escape hatch: when a command fails because of sandbox restrictions, Claude analyzes the failure and may retry the command with the `dangerouslyDisableSandbox` parameter. The retried command runs outside the sandbox, so it goes through the regular permission flow: in default mode you get a confirmation prompt; in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) the classifier evaluates the underlying command instead of prompting you. To be prompted on every unsandboxed retry even in auto mode, add an [ask rule](</docs/en/permissions#match-by-input-parameter>) for `Bash(dangerouslyDisableSandbox:true)`. You can disable this escape hatch by setting `"allowUnsandboxedCommands": false` in your [sandbox settings](</docs/en/settings#sandbox-settings>). When disabled, which the `/sandbox` Overrides tab shows as **Strict sandbox mode** , the `dangerouslyDisableSandbox` parameter is completely ignored and all commands must run sandboxed or be explicitly listed in `excludedCommands`. - Auto-allow mode works independently of your permission mode setting, with one exception: [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>). Even if you’re not in “accept edits” mode, sandboxed Bash commands run automatically when auto-allow is enabled. This means Bash commands that modify files within the sandbox boundaries execute without prompting, even when file edit tools would normally require approval.In plan mode, auto-allow doesn’t widen approvals. Bash commands outside the [built-in read-only set](</docs/en/permissions#read-only-commands>) prompt for approval even with auto-allow enabled, or go to the classifier when [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) is available and `useAutoModeDuringPlan` is on; in v2.1.212 through v2.1.217 they always prompted. Before v2.1.212, auto-allow ran sandboxed commands without a prompt in plan mode too. + +#### + +​ + +Regular permissions mode + +All Bash commands go through the regular permission flow, even when sandboxed. This provides more control but requires more approvals. + +#### + +​ + +The unsandboxed retry escape hatch + +Some commands can’t run inside the sandbox at all, such as tools that are incompatible with it or that need a host you haven’t allowed. When a command fails after the sandbox denied it access, Claude Code appends the violation details to the failed command’s output, so Claude sees which file path or network host the sandbox blocked. Rather than failing the task or requiring you to turn sandboxing off, Claude Code includes an escape hatch: when a command fails because of sandbox restrictions, Claude analyzes the failure and may retry the command with the `dangerouslyDisableSandbox` parameter. The retried command runs outside the sandbox, so it goes through the regular permission flow: in default mode you get a confirmation prompt; in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) the classifier evaluates the underlying command instead of prompting you. To be prompted on every unsandboxed retry even in auto mode, add an [ask rule](</docs/en/permissions#match-by-input-parameter>) for `Bash(dangerouslyDisableSandbox:true)`. You can disable this escape hatch by setting `"allowUnsandboxedCommands": false` in your [sandbox settings](</docs/en/settings#sandbox-settings>). When disabled, which the `/sandbox` Overrides tab shows as **Strict sandbox mode** , the `dangerouslyDisableSandbox` parameter is completely ignored and all commands must run sandboxed or be explicitly listed in `excludedCommands`. + +#### + +​ + +Temporary directories + +The session temp directory is writable inside the sandbox by default, alongside the working directory. Unless you disable filesystem isolation, Claude Code sets `$TMPDIR` to this directory for sandboxed commands, so tools that write temporary files work without extra configuration. Unsandboxed commands inherit your shell’s `$TMPDIR` unchanged, so while filesystem isolation is on, sandboxed and unsandboxed commands resolve `$TMPDIR` to different directories. To pass temporary files between the two, write them under the working directory instead. ## @@ -121,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. 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 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: Prefix| Meaning| Example ---|---|--- @@ -129,7 +159,7 @@ `~/`| Relative to home directory| `~/.kube` becomes `$HOME/.kube` `./` or no prefix| Relative to the project root for project settings, or to `~/.claude` for user settings| `./output` in `.claude/settings.json` resolves to `<project-root>/output` -This syntax differs from [Read and Edit permission rules](</docs/en/permissions#read-and-edit>), which use `//path` for absolute and `/path` for project-relative. Sandbox filesystem paths use standard conventions: `/tmp/build` is absolute. You can also deny write or read access using `sandbox.filesystem.denyWrite` and `sandbox.filesystem.denyRead`, and re-allow specific paths within a denied region using `sandbox.filesystem.allowRead`. When read rules overlap, the more specific path wins: +This syntax differs from [Read and Edit permission rules](</docs/en/permissions#read-and-edit>), which use `//path` for absolute and `/path` for project-relative. Sandbox filesystem paths use standard conventions: `/tmp/build` is absolute. For how Claude Code treats a trailing slash or a wildcard in these paths, see [Sandbox path prefixes](</docs/en/settings#sandbox-path-prefixes>). You can also deny write or read access using `sandbox.filesystem.denyWrite` and `sandbox.filesystem.denyRead`, and re-allow specific paths within a denied region using `sandbox.filesystem.allowRead`. When read rules overlap, the more specific path wins: Example rules| Result ---|--- @@ -392,6 +422,21 @@ ​ +Protected paths + +Inside the directories that sandboxed commands can write to, the sandbox still denies writes to the files Claude Code loads configuration and code from. A command that could edit those files could grant itself permissions, or add a hook or MCP server that Claude Code runs outside the sandbox. The permission system has its own [protected paths](</docs/en/permission-modes#protected-paths>), which control what Claude Code approves before a tool runs; the sandbox’s list applies to a command that is already running. It covers four groups of paths: + + * **In your working directory and the directories above it** : the `.claude` settings files, the `.claude/skills`, `.claude/agents`, `.claude/commands`, and `.claude/hooks` directories, `.mcp.json`, and the files Claude Code runs on its own, such as `.claude/workflows` and `.claude/scheduled_tasks.json` + * **In your working directory only** : shell startup files such as `.bashrc` and `.zshrc`, `.gitconfig`, the `.vscode` and `.idea` directories, and `hooks` and `config` inside `.git` + * **Files that would turn your working directory into a bare git repository** : `HEAD`, `objects`, and `refs` at the top level, plus `config` and `hooks` there when they already exist, even when the `config` directory belongs to your project rather than to git. On Linux and WSL2, the sandbox deletes a top-level `HEAD` file or `objects` or `refs` directory that appears while a sandboxed command is running + * **In`~/.claude`, or the directory `CLAUDE_CONFIG_DIR` points to**: most of its contents, plus `~/.claude.json` and the `.credentials.json` credential store + +If a symlink appears at a protected settings file’s path during the session, the sandbox also denies writes to the file it points to, starting with the next command. There is no way to exempt one of these paths: an `allowWrite` entry or an `Edit` allow rule that covers the path doesn’t lift the protection. The only way to turn the protection off is `filesystem.disabled`, which turns off filesystem isolation for every path. To see most of these paths resolved for your machine, run `/sandbox` and open the **Config** tab, which lists them under **Denied within allowed** , mixed in with your own `denyWrite` entries. If `git merge` or `git checkout` fails with `unable to unlink old` on one of these paths, see Troubleshooting. + +### + +​ + Network isolation Network access is controlled through a proxy server running outside the sandbox: @@ -545,6 +590,7 @@ * **Go-based CLIs fail TLS verification on macOS** : tools such as `gh`, `gcloud`, and `terraform` may fail TLS verification under Seatbelt. List these tools in `excludedCommands` to run them outside the sandbox. If you are using `httpProxyPort` with a MITM proxy and custom CA, set [`enableWeakerNetworkIsolation`](</docs/en/settings#sandbox-settings>) to `true` instead. * **`open`, `osascript`, or browser-based auth flows fail with error `-600` on macOS**: the sandbox blocks Apple Events by default. Set [`allowAppleEvents`](</docs/en/settings#sandbox-settings>) to `true` in your user, managed, or CLI settings to allow them. Project settings are ignored for this key. Enabling it removes code-execution isolation, since sandboxed commands can then launch other applications unsandboxed with no user prompt and send AppleScript commands to running applications, subject to the macOS automation-consent prompt (TCC). Alternatively, add the command to `excludedCommands` to run it outside the sandbox. * **`docker` commands fail**: `docker` is incompatible with the sandbox. Add `docker *` to `excludedCommands` to run it outside the sandbox. + * **A git command fails with`unable to unlink old`**: `git merge`, `git checkout`, and similar commands fail this way when they need to replace a file the sandbox denies writes to, whether that file is under a protected path such as `.claude/skills`, under one of your `denyWrite` entries, or outside the directories the sandbox lets commands write to at all. On Linux and WSL2 the error ends with `Read-only file system`. After the failure, Claude may offer to rerun the command outside the sandbox; approve that retry, or run the git command yourself in another terminal. If you’ve set `allowUnsandboxedCommands` to `false`, Claude can’t offer the retry, so run the command yourself or, if the same git command fails often, add that command to [`excludedCommands`](</docs/en/settings#sandbox-settings>). * **Bubblewrap fails to start inside a container** : in an unprivileged container, bubblewrap cannot mount a fresh `/proc` filesystem. Set [`enableWeakerNestedSandbox`](</docs/en/settings#sandbox-settings>) to `true` so the inner sandbox bind-mounts the container’s existing `/proc` instead. Only use this setting when the outer container already provides the isolation boundary you need, since it exposes process information to sandboxed commands that a fresh `/proc` mount would hide. * **`--dangerously-skip-permissions` fails as root**: this flag is blocked when running as root or via sudo on Linux and macOS, because root access combined with no permission prompts can modify any file or service on the system. The check is skipped automatically inside a recognized sandbox. To run autonomously in a container, use the [dev container](</docs/en/devcontainer>) configuration, which runs Claude Code as a non-root user. @@ -570,10 +616,6 @@ * **Filesystem permission escalation** : overly broad filesystem write permissions can enable privilege escalation attacks. Allowing writes to directories containing executables in `$PATH`, system configuration directories, or user shell configuration files such as `.bashrc` or `.zshrc` can lead to code execution in different security contexts when other users or system processes access these files. * **Linux sandbox strength** : the Linux implementation provides strong filesystem and network isolation but includes an `enableWeakerNestedSandbox` mode that enables it to work inside Docker environments without privileged namespaces, or on Linux hosts where unprivileged user namespaces are disabled by sysctl. This option considerably weakens security and should only be used when additional isolation is otherwise enforced. * **Apple Events on macOS** : the macOS sandbox blocks Apple Events by default. The `allowAppleEvents` setting lifts this restriction so tools such as `open` and `osascript` work, but it removes code-execution isolation: sandboxed commands can launch other applications unsandboxed with no user prompt, and can send AppleScript commands to running applications, subject to the per-app macOS automation-consent prompt (TCC). It is only honored from user, managed, or CLI settings. Project settings cannot enable it. - * **Settings files protected** : the sandbox automatically denies write access to the files a sandboxed command could otherwise edit its own policy through, unless you disable filesystem isolation, which turns these deny rules off. The protected set: - * Claude Code’s `settings.json` files at every scope, and the managed settings directory - * `.mcp.json` at the project root, and at the root of each directory added with [`--add-dir` or `/add-dir`](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) - * The target of any symlink that appears at a protected settings file path after startup, added to the deny list for the next command so a linked settings file can’t be edited through the link. Before v2.1.210, the deny rules didn’t resolve symlinks ###
modified Run prompts on a schedule View current →
--- a/scheduled-tasks.md +++ b/scheduled-tasks.md @@ -39,7 +39,7 @@ You can also pass a skill as the prompt, for example `/loop 20m /review-pr 1234`, to re-run that skill each iteration. As of v2.1.196, a scheduled fire only runs skills that Claude is [allowed to invoke on its own](</docs/en/skills#control-who-invokes-a-skill>). The following reach Claude as plain text instead of executing: * Built-in commands such as `/permissions`, `/model`, or `/clear` - * Skills marked [`disable-model-invocation: true`](</docs/en/skills#frontmatter-reference>), including the bundled `/verify` and `/code-review` skills. + * Skills marked [`disable-model-invocation: true`](</docs/en/skills#frontmatter-reference>), including the bundled `/verify` skill * Skills withheld from Claude by a [`skillOverrides`](</docs/en/skills#override-skill-visibility-from-settings>) setting or a `Skill` [deny rule](</docs/en/skills#restrict-claude%E2%80%99s-skill-access>) * [MCP prompts](</docs/en/mcp#use-mcp-prompts-as-commands>) such as `/mcp__github__list_prs`
modified Self-hosted environments View current →
--- a/self-hosted-environments.md +++ b/self-hosted-environments.md @@ -29,7 +29,7 @@ * **Plans** : public beta for Team and Enterprise organizations. Self-hosted environments are off by default; an [Owner or admin](</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 a scripted [`--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>), [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. * **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.
modified Customize sessions in self-hosted environments View current →
--- a/self-hosted-environments-configuration.md +++ b/self-hosted-environments-configuration.md @@ -92,7 +92,12 @@ `CLAUDE_RUNNER_API_BASE_URL`| Anthropic API base URL for session-scoped calls `CLAUDE_CODE_SESSION_ACCESS_TOKEN`| The session access token, for session-scoped API calls -The script must leave a working tree at `CLAUDE_RUNNER_CHECKOUT_PATH` checked out at the requested revision. Detached HEAD is fine; the runner creates the session’s working branch on top. The runner verifies the path contains a `.git` afterwards; if your hook materializes a non-git source such as Perforce or an unpacked tarball, set `CLAUDE_RUNNER_SKIP_GIT_VERIFY=1` in the runner’s environment to skip that check. Git-based flows such as working-branch creation and pushing results require a git checkout, so export outcomes from non-git trees with a `post-session` hook. The runner doesn’t pass a git credential to the hook. Instead, mint a per-session clone credential from the session’s identity: verify `CLAUDE_CODE_SESSION_ACCESS_TOKEN` with a standard JWT library against the JWKS endpoint under `CLAUDE_RUNNER_API_BASE_URL`, as described in [Verify the token from your service](</docs/en/self-hosted-environments-identity#verify-the-token-from-your-service>), then have your credential service issue a short-lived clone credential for the identity in the token’s `act` claim. `CLAUDE_RUNNER_CLAUDE_BIN` isn’t set in the checkout-hook environment, so the `decode-token` subcommand isn’t available here. Falling back to whatever git authentication the host already has, such as an SSH agent, credential helper, or `.netrc`, is also an option. A non-zero exit fails the session, and the tail of the script’s stderr is surfaced to the user. The runner removes the checkout path after the session ends. +The script must leave a working tree at `CLAUDE_RUNNER_CHECKOUT_PATH` checked out at the requested revision. Detached HEAD is fine; the runner creates the session’s working branch on top. The runner verifies the path contains a `.git` afterwards; if your hook materializes a non-git source such as Perforce or an unpacked tarball, set `CLAUDE_RUNNER_SKIP_GIT_VERIFY=1` in the runner’s environment to skip that check. Git-based flows such as working-branch creation and pushing results require a git checkout, so export outcomes from non-git trees with a `post-session` hook. The runner doesn’t pass a git credential to the hook. Instead, mint a per-session clone credential from the session’s identity: verify `CLAUDE_CODE_SESSION_ACCESS_TOKEN` with a standard JWT library against the JWKS endpoint under `CLAUDE_RUNNER_API_BASE_URL`, as described in [Verify the token from your service](</docs/en/self-hosted-environments-identity#verify-the-token-from-your-service>), then have your credential service issue a short-lived clone credential for the identity in the token’s `act` claim. `CLAUDE_RUNNER_CLAUDE_BIN` isn’t set in the checkout-hook environment, so the `decode-token` subcommand isn’t available here. Falling back to whatever git authentication the host already has, such as an SSH agent, credential helper, or `.netrc`, is also an option. When the hook exits non-zero, or exits 0 without leaving a usable checkout behind, what the runner does depends on the repository: + + * **A repository the session pushes results to** : the runner fails the session, and on a non-zero exit surfaces the tail of the script’s stderr to the user. + * **A repository the session only reads from** , such as a repository added to a running session: the runner logs a `[runner:warn]` line with the failure detail, posts a `Skipped` step to the session, removes whatever the hook left at the checkout path, and continues with the remaining repositories. When the runner can’t remove the path immediately, it retries the removal at session end. If skipping leaves the session with no repository at all, the runner fails the session anyway. + +Before v2.1.228, the runner failed the session on a hook failure for any repository, so a read-only repository the hook couldn’t serve failed the session again on every fresh runner the session resumed on. The runner removes the checkout path after the session ends. ###
modified Deploy self-hosted environments to production View current →
--- a/self-hosted-environments-deploy.md +++ b/self-hosted-environments-deploy.md @@ -52,7 +52,7 @@ `code.claude.com` and `claude.com`| 443| Documentation lookups by the built-in claude-code-guide agent and pre-approved WebFetch requests during sessions. Blocking these hosts only affects documentation lookups. `*.frame.claudeusercontent.com`| 443| Only when the [Artifact tool](</docs/en/artifacts#availability>) is available for sessions in your organization; defaults vary by plan, per the availability table there. Set `CLAUDE_CODE_DISABLE_ARTIFACT=1` on the runner to keep the tool disabled regardless of the organization setting. `raw.githubusercontent.com`| 443| Only for the changelog fetch behind `/release-notes` and the release notes shown after a CLI version change. Suppressed by `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1`. -`registry.npmjs.org`| 443| Only when a session installs a plugin that includes Node.js dependencies, or when an `npx`-launched MCP server runs +`registry.npmjs.org`| 443| When a session installs a plugin, both for fetching npm-source plugin packages and for installing a plugin’s Node.js dependencies, or when an `npx`-launched MCP server runs `http-intake.logs.us5.datadoghq.com`| 443| Anthropic operational metrics. Only when `CLAUDE_CODE_BYOC_ENABLE_DATADOG=1` is set; off by default in self-hosted environments. `browser-intake-us5-datadoghq.com`| 443| Anthropic error-report uploads, sent only when [error reporting](</docs/en/data-usage#telemetry-services>) is enabled for the session’s account. Suppressed by `DISABLE_ERROR_REPORTING=1` or `DISABLE_TELEMETRY=1`. @@ -278,7 +278,7 @@ Keep the base directory and capacity identical across runners -If a runner dies mid-session, the server requeues the session and another runner in the environment picks it up. That runner derives the checkout path from its own `--base-dir` and `--capacity`: `--capacity 1` checks out directly under `--base-dir`, and a `--capacity` above `1` uses per-session worktrees instead. When runners in the same environment use different values for either flag, the resumed session’s working directory changes, and absolute paths the agent recorded earlier, in edits, tool calls, or its own notes, point at a location that no longer exists. Use the same `--base-dir` and `--capacity` on every runner in an environment, and don’t use a per-host value such as an instance ID or hostname. The base directory must be writable by the user the runner runs as: the runner creates per-session directories under it when each session starts and doesn’t check it at startup, so a missing or read-only base directory typically shows up as sessions that fail immediately after pickup rather than as a startup error. The default is `/workspace`, which a runner running as root creates on first use; for a non-root runner, create the directory and give that user ownership before starting the runner, or point `--base-dir` at a directory the user already owns. +If a runner dies mid-session, the server requeues the session and another runner in the environment picks it up. That runner derives the checkout path from its own `--base-dir` and `--capacity`: `--capacity 1` checks out directly under `--base-dir`, and a `--capacity` above `1` uses per-session worktrees instead. When runners in the same environment use different values for either flag, the resumed session’s working directory changes, and absolute paths the agent recorded earlier, in edits, tool calls, or its own notes, point at a location that no longer exists. Use the same `--base-dir` and `--capacity` on every runner in an environment, and don’t use a per-host value such as an instance ID or hostname. The base directory defaults to `/workspace`. The runner needs write access to it. At startup, before registering, the runner creates the directory and confirms it can write to it, and exits with `cannot create or write to base directory` when it can’t. A runner started as root creates the default `/workspace` itself. For a non-root runner, create the directory and give the runner’s user ownership before starting the runner, or point `--base-dir` at a directory that user already owns. ## @@ -371,13 +371,14 @@ Common issues: * **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 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, build tools that aren’t installed, and a base directory the runner’s user can’t write to. For the last one the error is `EACCES` on a path under `--base-dir`, default `/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. - * **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. + * **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. + * **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. * **Sessions take minutes to start** : the initial clone usually dominates. Watch the `claude_code_self_hosted_runner_session_init_duration_seconds` [metric](</docs/en/self-hosted-environments-reference#prometheus-metrics>) to confirm, and cut the clone with a pre-warmed checkout or a smaller `CLAUDE_RUNNER_FETCH_DEPTH`. * **Pod is killed mid-drain** : raise `terminationGracePeriodSeconds` to at least the value the runner logs at startup. See Shutdown timing. -The runner writes its lifecycle log, including `[runner:fatal]` lines, to stdout, and debug output to stderr, all as plain-text lines rather than JSON; capture both streams with `--log-file`, which also lets `self-hosted-runner doctor` tail them, or with your platform’s log collection. Each session’s child process writes a separate debug log; on failure the runner preserves the log, prints the log’s path in the runner log, and surfaces the log’s tail alongside the session in claude.ai/code. +Once logging is initialized, the runner writes its lifecycle log, including `[runner:fatal]` lines, to stdout, and debug output to stderr, all as plain-text lines rather than JSON. The startup failures described in the troubleshooting entries above print to stderr before that point. Capture both streams with `--log-file`, which also lets `self-hosted-runner doctor` tail them, or with your platform’s log collection. Each session’s child process writes a separate debug log. On failure the runner preserves the log, prints the log’s path in the runner log, and surfaces the log’s tail alongside the session in claude.ai/code. ##
modified Self-hosted environments quickstart View current →
--- a/self-hosted-environments-quickstart.md +++ b/self-hosted-environments-quickstart.md @@ -77,11 +77,7 @@ (umask 077 && cat > /etc/claude/environment-secret) -Create the base directory, replacing `<writable-dir>` here and in the next command with an absolute path that the user running the runner can write to. The runner checks repositories out and creates per-session directories under this path. Without `--base-dir` it uses `/workspace`, which only works if that directory already exists and is writable or the runner runs as root. - - mkdir -p '<writable-dir>' - -Then start the runner with `--environment-secret-file` and `--base-dir`. The runner registers with your environment and begins polling for work. If the runner exits, restart it by hand. Production deployments run the runner under an orchestrator that restarts exited runners, normally with a fresh filesystem per restart; [Reuse a pre-warmed checkout](</docs/en/self-hosted-environments-deploy#reuse-a-pre-warmed-checkout>) covers the supported persistent-disk setup. +Choose a base directory, replacing `<writable-dir>` in the runner command below with an absolute path that the runner can write to or create. The runner creates the directory at startup, then checks repositories out and creates per-session directories under it. Without `--base-dir` it uses `/workspace`, which only works if that directory already exists and is writable or you start the runner as root.If the runner can’t create or write to the path, it exits at startup with an error naming the directory instead of registering. See [Troubleshooting](</docs/en/self-hosted-environments-deploy#troubleshooting>).Then start the runner with `--environment-secret-file` and `--base-dir`. The runner registers with your environment and begins polling for work. If the runner exits, restart it by hand. Production deployments run the runner under an orchestrator that restarts exited runners, normally with a fresh filesystem per restart; [Reuse a pre-warmed checkout](</docs/en/self-hosted-environments-deploy#reuse-a-pre-warmed-checkout>) covers the supported persistent-disk setup. claude self-hosted-runner --environment-secret-file '/etc/claude/environment-secret' --base-dir '<writable-dir>'
modified Self-hosted environments reference View current →
--- a/self-hosted-environments-reference.md +++ b/self-hosted-environments-reference.md @@ -13,7 +13,7 @@ Flag| Env var| Default| Description ---|---|---|--- `--api-url <url>`| none| `https://api.anthropic.com`| API base URL. Override only for testing. -`--base-dir <path>`| `SELF_HOSTED_RUNNER_BASE_DIR`| `/workspace`| Directory for repository checkouts and per-session working directories. The runner creates it and its subdirectories on first use, so the user running the runner needs write access to this path or its parent. 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>). +`--base-dir <path>`| `SELF_HOSTED_RUNNER_BASE_DIR`| `/workspace`| 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. 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>). `--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`| Warn without refusing (`warn`, the default), enforce (`enforce`), or disable (`off`) 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`. See [Harden your deployment](</docs/en/self-hosted-environments-deploy#harden-your-deployment>).
modified Test self-hosted environments end to end View current →
--- a/self-hosted-environments-testing.md +++ b/self-hosted-environments-testing.md @@ -83,6 +83,14 @@ 2. Waits for the reply to appear in `$E2E_REPLY_DIR/<session_id>.txt`, written by the Stop hook on the runner once the turn completes. 3. Sends a follow-up with `claude -p "<message>" --cloud <session_id> --output-format json` (see [Send a follow-up message to a running session](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>)), which posts a user event to the existing session and exits. 4. Waits for the follow-up’s reply the same way as step 2. + +### + +​ + +`--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#available-settings>) 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 @@ -122,7 +122,7 @@ Managed-only settings -Most [settings keys](</docs/en/settings#available-settings>) work in any scope. A handful of keys are only read from managed settings and have no effect when placed in user or project settings files. See [managed-only settings](</docs/en/permissions#managed-only-settings>) for the full list. Any setting not on that list can still be placed in managed settings and takes the highest precedence, apart from the exceptions listed in the [settings reference’s precedence section](</docs/en/settings#settings-precedence>). +Most [settings keys](</docs/en/settings#available-settings>) work in any scope. A handful of keys are only read from managed settings and have no effect when placed in user or project settings files. See [managed-only settings](</docs/en/permissions#managed-only-settings>) for the full list. ### @@ -217,7 +217,7 @@ "forceRemoteSettingsRefresh": true } -You can also set this key in an [endpoint-managed](</docs/en/settings#settings-files>) MDM profile or system `managed-settings.json` file to enforce fail-closed behavior on first launch, before any server payload has been delivered. As of v2.1.191, this flag is an exception to the precedence rule above: it is honored when set in any admin-controlled managed source even if a cached server-managed payload is also present, so an MDM-delivered value is not ignored when server-managed settings exist. When a [`policyHelper`](</docs/en/settings#compute-managed-settings-with-a-policy-helper>) is configured, its output replaces every other managed source, this key included. The settings fetch also sends a `Cache-Control: no-cache` header so intermediate HTTP proxies don’t serve a stale response. Before enabling this setting, ensure your network policies allow connectivity to `api.anthropic.com`. If that endpoint is unreachable, the CLI exits at startup and users cannot start Claude Code. As of v2.1.139, the `claude auth` subcommands such as `claude auth login` are exempt from this check, so users can re-authenticate when expired credentials are the reason the settings fetch fails. +You can also set this key in an [endpoint-managed](</docs/en/settings#settings-files>) MDM profile or system `managed-settings.json` file to enforce fail-closed behavior on first launch, before any server payload has been delivered. As of v2.1.191, this flag is an exception to the precedence rule above: it is honored when set in any admin-controlled managed source even if a cached server-managed payload is also present, so an MDM-delivered value is not ignored when server-managed settings exist. When a [`policyHelper`](</docs/en/settings#compute-managed-settings-with-a-policy-helper>) is configured, its output replaces every other managed source, this key included. The settings fetch also sends a `Cache-Control: no-cache` header so intermediate HTTP proxies don’t serve a stale response. Before enabling this setting, ensure your network policies allow connectivity to `api.anthropic.com`. If that endpoint is unreachable, the CLI exits at startup and users cannot start Claude Code. The `claude auth` subcommands such as `claude auth login` are exempt from this check, so users can re-authenticate when expired credentials are the reason the settings fetch fails. ### @@ -232,7 +232,25 @@ * **Hook configurations** : any hook definition * **Managed CLAUDE.md content** : a `claudeMd` value delivered through managed settings -When these settings are present, users see a security dialog explaining what is being configured. Users must approve to proceed. If a user rejects the settings, Claude Code exits. If an interactive session can’t show the dialog, Claude Code doesn’t apply the delivered settings and keeps the last-approved settings; the dialog appears in the next session that can show it. Requires Claude Code v2.1.211 or later. +When these settings are present, users see a security dialog explaining what is being configured. Users must approve to proceed. If a user rejects the settings, Claude Code exits. + +#### + +​ + +Approval memory + +Claude Code records your approval in your configuration directory, `~/.claude` unless you set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>). What it records depends on the credential the settings fetch uses: + + * **A claude.ai login saved by`/login` or `claude auth login`**: one approval per organization, held by the account that approved most recently. + * **Any other credential** , such as a [Claude apps gateway](</docs/en/claude-apps-gateway>), an API key, or `CLAUDE_CODE_OAUTH_TOKEN`: one approval for the delivered settings, kept with the cached copy of the settings in that configuration directory. Claude Code shows the dialog again when the settings that require approval change, and after you run `/logout` or `claude auth logout`, which delete the cached copy. + +With a saved claude.ai login: + + * If you sign out and back in, or switch to another organization and later return, Claude Code doesn’t show the dialog again while those settings are unchanged, unless another account approved them for that organization in the same configuration directory in between. + * If you sign in to the same organization with a different account, Claude Code shows the dialog again even when the settings are unchanged. That account’s approval replaces the previous one, so when you switch back, Claude Code shows the dialog once more. + +If an interactive session can’t show the dialog, Claude Code doesn’t apply the delivered settings and keeps the last-approved settings; the dialog appears in the next session that can show it. Requires Claude Code v2.1.211 or later. A non-interactive run, such as `claude -p` or an Agent SDK session, can’t show the dialog. When the delivered settings would require approval, Claude Code applies them for that run only: it doesn’t record them as approved or write them to the local cache, and the next interactive session shows the dialog. Until a user approves in an interactive session, each non-interactive run fetches the settings again at startup. Before v2.1.207, a non-interactive run saved the settings as approved, so later interactive sessions never showed the dialog for them.
modified Persist sessions to external storage View current →
--- a/session-storage.md +++ b/session-storage.md @@ -83,13 +83,13 @@ Method| Required| Called when ---|---|--- `append`| Yes| After each batch of transcript entries is written locally. Entries are JSON-safe objects, one per line in the local JSONL. -`load`| Yes| Before the subprocess spawns when `resume` is set, and once per session when listing falls back from `listSessionSummaries`. Return `null` if the session is unknown. +`load`| Yes| Before the subprocess spawns when `resume` is set or `continue: true` resolves the newest store session, and once per session when listing falls back from `listSessionSummaries`. Return `null` if the session is unknown. `listSessions`| No| By `listSessions({ sessionStore })` and by `query()`/`startup()` with `continue: true`. If undefined, `continue: true` throws, and `listSessions({ sessionStore })` throws unless `listSessionSummaries` is implemented. `listSessionSummaries`| No| By `listSessions({ sessionStore })` to read metadata for all sessions in one call. Maintain the summaries inside `append`. If undefined, listing falls back to `listSessions` plus a per-session `load`. `delete`| No| By `deleteSession({ sessionStore })`. Deleting the main key (no `subpath`) must cascade to all subkeys for that session and also remove the session’s summary entry, so a deleted session stops appearing in `listSessionSummaries`. If undefined, deletion is a no-op, which suits append-only backends. `listSubkeys`| No| During resume, to discover subagent transcripts. If undefined, only the main transcript is restored. -In a `SessionSummaryEntry`, `mtime` is the sidecar’s storage write time and must share a clock source with the `mtime` values `listSessions` returns. `data` is opaque SDK-owned state; persist it verbatim without interpreting it. Build the entries by calling the exported `foldSessionSummary` helper, `fold_session_summary` in Python, on each batch inside `append`. Skip batches whose key has a `subpath`; subagent transcripts must not contribute to the main session’s summary. The fold never sets `mtime`: stamp it at persist time, through the `options.mtime` argument in TypeScript or by overwriting the field on the returned entry in Python. Concurrent `append` calls for the same session can race on the sidecar, so serialize the read-fold-write with a transaction, a compare-and-swap, or a per-session lock; the fold itself is pure. +In a `SessionSummaryEntry`, `mtime` is the sidecar’s storage write time and must share a clock source with the `mtime` values `listSessions` returns. `data` is opaque SDK-owned state; persist it verbatim without interpreting it. Build the entries by calling the exported `foldSessionSummary` helper, `fold_session_summary` in Python, on each batch inside `append`. Skip batches whose key has a `subpath`; subagent transcripts must not contribute to the main session’s summary. The fold never sets `mtime`: stamp it at persist time, through the `options.mtime` argument in TypeScript or by overwriting the field on the returned entry in Python. Concurrent `append` calls for the same session can race on the sidecar, so serialize the read-fold-write with a transaction, a compare-and-swap, or a per-session lock; the fold itself is pure. For what the SDK does with the transcript `load` returns, see Resume from the store. ## @@ -259,7 +259,37 @@ Dual-write architecture -The store is a mirror, not a replacement. The Claude Code subprocess always writes to local disk first; the SDK then forwards each batch to `append()`. If you want the local copy to be ephemeral, point `CLAUDE_CONFIG_DIR` at a temp directory in `options.env`. Because the mirror depends on local writes, the TypeScript SDK throws if you combine `sessionStore` with `persistSession: false`. Both SDKs also throw if you combine the store with file checkpointing, `enableFileCheckpointing` in TypeScript or `enable_file_checkpointing` in Python, since file-history backup blobs are written directly to local disk and are not mirrored to the store. +The Claude Code subprocess always writes each batch of transcript entries to local disk first, and the SDK then forwards the same batch to your store’s `append()`, so the store is a mirror of the local transcript rather than a replacement for it. Which copy outlives the run depends on how the run started: + + * **Fresh session, or a resume when the store has nothing for the session** : the local transcript under your config directory outlives the run, and the store receives a copy. + * **Runresumed from the store**: the local copy is deleted at run end, so the store holds the only durable copy. + +If you don’t want a fresh session to leave a transcript on local disk, set `CLAUDE_CONFIG_DIR` to a temp directory in `options.env`. A run resumed from the store already deletes its local copy, so it needs no such setting. In TypeScript, spread `process.env` into `env` as well, since the [`env` option](</docs/en/agent-sdk/typescript#options>) replaces the subprocess environment. If your app signs in through files in the config directory, such as OAuth credentials or an `apiKeyHelper` in your user `settings.json`, copy those files into the temp directory first, or set `ANTHROPIC_API_KEY` in `env` instead. Otherwise the run fails with `Not logged in`. Two options conflict with the mirror, and the SDK throws at startup if you combine either with a store: + + * **`persistSession: false`** in TypeScript: turns off the local writes the mirror is built from. The Python SDK has no equivalent option. + * **File checkpointing** , `enableFileCheckpointing` in TypeScript or `enable_file_checkpointing` in Python: writes its file backups straight to local disk, and the SDK doesn’t mirror them to the store. + +### + +​ + +Resume from the store + +When you pass `resume`, or `continue: true` in TypeScript or `continue_conversation=True` in Python, together with a store, the SDK asks the store for a transcript before it spawns the subprocess: + + * **`resume`** : the SDK asks for the session whose ID you passed. + * **`continue: true`** or **`continue_conversation=True`** : the SDK asks for the store’s newest session. + +When the store returns the transcript, the SDK writes it into a temporary config directory, runs the subprocess with `CLAUDE_CONFIG_DIR` pointing there, and deletes the directory when the run ends. The local transcript that run writes is deleted with it, which is why the store holds the only durable copy on this path. The SDK also seeds the temporary directory with files from your real config directory. What it copies differs by language: + + * **TypeScript** : credentials, `.claude.json`, and your user `settings.json`. From `settings.json` it strips the three keys that misbehave under a temporary config directory: `enabledPlugins`, `extraKnownMarketplaces`, and any `CLAUDE_CONFIG_DIR` in the file’s `env` block. Auth configured in settings, such as [`apiKeyHelper`](</docs/en/settings#available-settings>), works when you resume from the store. Before Agent SDK v0.3.222, the TypeScript SDK copied only credentials and `.claude.json`. + * **Python** : credentials and `.claude.json` only, so an app that authenticates through `apiKeyHelper` in your user `settings.json` fails with `Not logged in` when resuming from a store. An `apiKeyHelper` in managed or project settings still works, because Claude Code reads those files from locations that `CLAUDE_CONFIG_DIR` doesn’t affect. + +When the store has nothing for the session, the SDK runs under your real config directory instead, and the outcome depends on which option you passed: + + * **`resume`** : both SDKs pass the ID through to the subprocess, which resumes the local transcript exactly as `resume` does without a store. + * **`continue: true`** in TypeScript: the SDK starts a fresh session. + * **`continue_conversation=True`** in Python: the SDK continues from the newest local session. ### @@ -267,7 +297,7 @@ Mirror writes are best-effort -If `append()` rejects, the SDK retries the batch up to two more times with a short backoff, for at most three attempts in total. A call that times out isn’t retried, since the original call may still land. If the batch still fails, the error is logged, a `{ type: "system", subtype: "mirror_error" }` message is emitted into the iterator, the batch is dropped, and the query continues. The local transcript is already durable on disk, so a store outage doesn’t interrupt the agent or lose data locally. Monitor for `mirror_error` if you need to detect store data loss. Because a retried batch can re-deliver entries that already landed, deduplicate by `entry.uuid` in your `append()` implementation. +If `append()` rejects, the SDK retries the batch up to two more times with a short backoff, for at most three attempts in total. A call that times out isn’t retried, since the original call may still land. If the batch still fails, the SDK logs the error, emits a `{ type: "system", subtype: "mirror_error" }` message into the iterator, drops the batch, and continues the query. Because a retried batch can re-deliver entries that already landed, deduplicate by `entry.uuid` in your `append()` implementation. A store outage doesn’t interrupt the agent, since the subprocess writes locally first. Monitor for `mirror_error` if you need to detect store data loss. On a run resumed from the store, a dropped batch has no surviving copy once the run ends. ### @@ -299,7 +329,7 @@ Retention -The SDK never deletes from your store on its own. Retention is the adapter’s responsibility: implement TTLs, S3 lifecycle policies, or scheduled cleanup according to your compliance requirements. Local transcripts under `CLAUDE_CONFIG_DIR` are swept independently by the `cleanupPeriodDays` setting. +The SDK never deletes from your store on its own. Retention is the adapter’s responsibility: implement TTLs, S3 lifecycle policies, or scheduled cleanup according to your compliance requirements. Local transcripts under `CLAUDE_CONFIG_DIR` are swept independently by the `cleanupPeriodDays` setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). A run resumed from the store leaves no local transcript, so for those runs your store’s retention is the only retention there is. ##
modified Work with sessions View current →
--- a/sessions.md +++ b/sessions.md @@ -267,7 +267,7 @@ You should see a response that builds on the earlier analysis instead of starting fresh. That confirms the agent resumed the session with its prior context intact. -Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, or under `$CLAUDE_CONFIG_DIR/projects/<encoded-cwd>/*.jsonl` if you set the `CLAUDE_CONFIG_DIR` environment variable. `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-`, so `/Users/me/proj` becomes `-Users-me-proj`.You can resume from any working directory: +Claude Code stores sessions under `~/.claude/projects/<encoded-cwd>/*.jsonl`. If you set the `CLAUDE_CONFIG_DIR` environment variable, look under `$CLAUDE_CONFIG_DIR/projects/` instead. To find your session’s directory, replace every non-alphanumeric character in the absolute working directory with `-`: `/Users/me/proj` becomes `-Users-me-proj`. For a working directory whose converted name exceeds 200 characters, Claude Code [truncates the name and appends a hash](</docs/en/sessions#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`.You can resume from any working directory: * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) for the exact lookup order and how duplicate copies are handled. * **Same machine only** : the session file still needs to exist on the current machine.
modified Claude Code settings View current →
Show diff (149 lines)
--- a/settings.md +++ b/settings.md @@ -225,7 +225,7 @@ `askUserQuestionTimeout`| **Default** : `"never"`. Idle time before an unanswered [`AskUserQuestion`](</docs/en/tools-reference>) dialog auto-continues with whatever options you’d already selected. Accepts `"60s"`, `"5m"`, `"10m"`, or `"never"`. With the default, questions wait until you answer them. Appears in `/config` as **Question auto-continue timeout** , which writes this key to user settings. Not read from project or local settings. Requires Claude Code v2.1.200 or later| `"5m"` `attribution`| Customize attribution for git commits and pull requests. See Attribution settings| `{"commit": "🤖 Generated with Claude Code", "pr": ""}` `autoCompactEnabled`| **Default** : `true`. Automatically compact the conversation when context approaches the limit. Appears in `/config` as **Auto-compact**. To disable via environment variable, set [`DISABLE_AUTO_COMPACT`](</docs/en/env-vars>) in `env`| `false` -`autoCompactWindow`| How full the context window gets before Claude Code [compacts automatically](</docs/en/context-window#when-your-context-fills-up>), in tokens from `100000` to `1000000`. When unset, Claude Code uses a window tuned for your model. Set it with the [`/autocompact`](</docs/en/commands#all-commands>) command, which writes this key to user settings; the [`--autocompact`](</docs/en/cli-reference#cli-flags>) flag and the [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>) environment variable can override it. [Set the auto-compact window](</docs/en/context-window#set-the-auto-compact-window>) covers how they interact| `500000` +`autoCompactWindow`| How full the context window gets before Claude Code [compacts automatically](</docs/en/context-window#when-your-context-fills-up>), in tokens from `100000` to `1000000`. When unset, Claude Code uses a window tuned for your model. Set it with the [`/autocompact`](</docs/en/commands#all-commands>) command, which writes this key to user settings; the [`--autocompact`](</docs/en/cli-reference#cli-flags>) flag and the [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>) environment variable can override it. [Set the auto-compact window](</docs/en/model-config#set-the-auto-compact-window>) covers how they interact| `500000` `autoMemoryDirectory`| Custom directory for [auto memory](</docs/en/memory#storage-location>) storage. Accepts an absolute path or a `~/`-prefixed path. From project or local settings, this is honored only after you accept the workspace trust dialog, since a cloned repository can supply this file| `"~/my-memory-dir"` `autoMemoryEnabled`| **Default** : `true`. Enable [auto memory](</docs/en/memory#enable-or-disable-auto-memory>). When `false`, Claude does not read from or write to the auto memory directory. You can also toggle this with `/memory` during a session. To disable via environment variable, set [`CLAUDE_CODE_DISABLE_AUTO_MEMORY`](</docs/en/env-vars>) in `env`| `false` `autoMode`| Customize what the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier blocks and allows. Contains `environment`, `allow`, `soft_deny`, and `hard_deny` arrays of prose rules. Include the literal string `"$defaults"` in an array to inherit the built-in rules at that position. See [Configure auto mode](</docs/en/auto-mode-config>). Read from user settings, the `--settings` flag, and managed settings only. Ignored in project `.claude/settings.json` and local `.claude/settings.local.json`. Before v2.1.207, `.claude/settings.local.json` was also read| `{"soft_deny": ["$defaults", "Never run terraform apply"]}` @@ -237,17 +237,17 @@ `awsAuthRefresh`| Custom script that modifies the `.aws` directory (see [advanced credential configuration](</docs/en/amazon-bedrock#advanced-credential-configuration>))| `aws sso login --profile myprofile` `awsCredentialExport`| Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](</docs/en/amazon-bedrock#advanced-credential-configuration>))| `/bin/generate_aws_grant.sh` `axScreenReader`| Render screen-reader friendly output: flat text without decorative borders or animations. Screen-reader mode uses the classic renderer, so the `tui` setting has no effect while it is active; attached [background sessions](</docs/en/agent-view>) still render fullscreen. The [`CLAUDE_AX_SCREEN_READER`](</docs/en/env-vars>) environment variable and the [`--ax-screen-reader`](</docs/en/cli-reference#cli-flags>) flag take precedence. Requires Claude Code v2.1.181 or later| `true` -`blockedMarketplaces`| (Managed settings only) Blocklist of marketplace sources. Enforced on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace added before the policy was set cannot be used to fetch plugins. Blocked sources are checked before downloading, so they never touch the filesystem. See [Managed marketplace restrictions](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>)| `[{ "source": "github", "repo": "untrusted/plugins" }]` +`blockedMarketplaces`| (Managed settings only) Blocklist of marketplace sources. Enforced on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace added before the policy was set cannot be used to fetch plugins. Blocked sources are checked before downloading, so they never touch the filesystem. A `github` entry may use the owner-wildcard form `"owner/*"` to block every repository under that GitHub owner. Requires Claude Code v2.1.223 or later. See [Managed marketplace restrictions](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>)| `[{ "source": "github", "repo": "untrusted/plugins" }]` `browserExternalPageTools`| (Managed settings only) Set to `"disabled"` to prevent Claude from using tools to read or act on external pages in the desktop app’s [Browser pane](</docs/en/desktop#browse-external-sites>). Users can still navigate to external sites themselves, and local dev server previews are unaffected| `"disabled"` `channelsEnabled`| (Managed settings only) Allow [channels](</docs/en/channels>) for the organization. On claude.ai Team and Enterprise plans, channels are blocked when this is unset or `false`. For [Anthropic Console](</docs/en/authentication#claude-console-authentication>) accounts using API key authentication, channels are allowed by default unless your organization deploys managed settings, in which case this key must be set to `true`| `true` `claudeMd`| (Managed settings only) CLAUDE.md-style instructions injected as organization-managed memory. Only honored when set in managed or policy settings and ignored in user, project, and local settings. See [organization-wide CLAUDE.md](</docs/en/memory#deploy-organization-wide-claude-md>)| `"Always run make lint before committing."` `claudeMdExcludes`| Glob patterns or absolute paths of `CLAUDE.md` files to skip when loading [memory](</docs/en/memory>). Patterns match against absolute file paths. Only applies to user, project, and local memory; managed policy files cannot be excluded| `["**/vendor/**/CLAUDE.md"]` -`cleanupPeriodDays`| **Default** : `30` days, minimum `1`. Claude Code deletes [session files and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than this period at startup. To disable transcript writes entirely, see [Plaintext storage](</docs/en/claude-directory#plaintext-storage>).| `20` +`cleanupPeriodDays`| **Default** : `30` days, minimum `1`. Claude Code deletes [session files and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than this period at startup, as long as it can safely determine the retention period. To disable transcript writes entirely, see [Plaintext storage](</docs/en/claude-directory#plaintext-storage>).| `20` `companyAnnouncements`| Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random.| `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` `crossSessionInbound`| How this session treats inbound [cross-session messages](</docs/en/cross-session-messaging#control-inbound-messages>) from your other Claude Code sessions: `"accept"` delivers them to Claude, `"hold"` shows a notice for each message without delivering it, and `"refuse"` drops them. When no value applies, Claude Code decides per message from the two sessions’ permission-mode classes; see [Control inbound messages](</docs/en/cross-session-messaging#control-inbound-messages>) for the rules. Claude Code reads managed settings first, then the `--settings` flag, then user settings, and applies the first value found; a value in project or local settings applies only when it’s stricter, on the `accept` < `hold` < `refuse` ladder, than the value those trusted sources give. When none of the trusted sources sets a value, a project or local `hold` or `refuse` still applies, replacing the per-message default. Requires Claude Code v2.1.224 or later| `"hold"` `defaultShell`| **Default** : `"bash"`, or `"powershell"` on Windows when Bash isn’t available. Default shell for input-box `!` commands. Accepts `"bash"` or `"powershell"`. Setting `"powershell"` routes interactive `!` commands through PowerShell when the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) is enabled: it’s on by default on Windows without Git Bash, and `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` enables it elsewhere| `"powershell"` `deniedMcpServers`| When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](</docs/en/managed-mcp>)| `[{ "serverName": "filesystem" }]` -`dialogExpiry`| **Default** : `"5m"`. Deadline for dialogs Claude Code forwards to a remote client, such as a [Remote Control](</docs/en/remote-control>) or SDK host, for example the model-choice prompt shown after a safety refusal, and for a [held cross-session message](</docs/en/cross-session-messaging#control-inbound-messages>) awaiting approval. When no answer arrives before the deadline, Claude Code cancels the dialog and continues with its no-action default; when the deadline passes on a message the [inbound default](</docs/en/cross-session-messaging#control-inbound-messages>) holds, Claude Code drops it. Permission prompts and [`AskUserQuestion`](</docs/en/tools-reference#askuserquestion-tool-behavior>) questions use their own flows and aren’t governed by this deadline. Accepts `"60s"`, `"5m"`, `"10m"`, or `"never"`, which disables the deadline. The [`CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS`](</docs/en/env-vars>) environment variable overrides this setting. Read from user, managed, and `--settings` sources only. Requires Claude Code v2.1.224 or later| `"10m"` +`dialogExpiry`| **Default** : `"5m"`. Deadline for dialogs Claude Code [forwards to a remote client](</docs/en/remote-control#limitations>), such as a Remote Control or SDK host, and for the approval dialog for a [held cross-session message](</docs/en/cross-session-messaging#control-inbound-messages>). When no answer arrives before the deadline, Claude Code cancels the dialog and continues with its no-action default. Permission prompts and [`AskUserQuestion`](</docs/en/tools-reference#askuserquestion-tool-behavior>) questions use their own flows and aren’t governed by this deadline. Accepts `"60s"`, `"5m"`, `"10m"`, or `"never"`, which disables the deadline. The [`CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS`](</docs/en/env-vars>) environment variable overrides this setting. Read from user, managed, and `--settings` sources only. Requires Claude Code v2.1.224 or later| `"10m"` `disableAgentView`| Set to `true` to turn off [background agents and agent view](</docs/en/agent-view>): `claude agents`, `--bg`, `/background`, and the on-demand supervisor. Typically set in [managed settings](</docs/en/permissions#managed-settings>). Equivalent to setting `CLAUDE_CODE_DISABLE_AGENT_VIEW` to `1`| `true` `disableAllHooks`| Disable all [hooks](</docs/en/hooks>) and any custom [status line](</docs/en/statusline>)| `true` `disableArtifact`| Set to `true` to disable the [Artifact](</docs/en/artifacts>) tool, which publishes session output as a private web page on claude.ai. Equivalent to setting `CLAUDE_CODE_DISABLE_ARTIFACT` to `1`| `true` @@ -388,9 +388,9 @@ `ask`| Array of permission rules to ask for confirmation upon tool use. See Permission rule syntax below| `[ "Bash(git push *)" ]` `deny`| Array of permission rules to deny tool use. Use this to exclude sensitive files from Claude Code access. Tool names accept glob patterns: `"*"` denies every tool and `"mcp__*"` denies every MCP tool. Deny rules can’t remove [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) while any other tool remains. See Permission rule syntax and [Bash permission limitations](</docs/en/permissions#tool-specific-permission-rules>)| `[ "WebFetch", "Bash(curl *)", "Read(./.env)", "Read(./secrets/**)" ]` `additionalDirectories`| Additional [working directories](</docs/en/permissions#working-directories>) for file access. Most `.claude/` configuration is [not discovered](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) from these directories| `[ "../docs/" ]` -`defaultMode`| Default [permission mode](</docs/en/permission-modes>) when opening Claude Code. Valid values: `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions`, and `manual` as an alias for `default`, the mode labeled Manual in the CLI, the VS Code and JetBrains extensions, and the desktop app. The `manual` alias requires Claude Code v2.1.200 or later. `auto` is ignored when set in project or local settings, so a repository can’t grant itself auto mode; set it in `~/.claude/settings.json` instead. Before v2.1.142, project settings could set `auto`. The `--permission-mode` CLI flag overrides this setting for a single session| `"acceptEdits"` +`defaultMode`| Default [permission mode](</docs/en/permission-modes>) for new sessions. In sessions the [VS Code extension](</docs/en/vs-code>) starts, the extension resolves the starting mode instead. Valid values: `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions`, and `manual` as an alias for `default`, the mode labeled Manual in the CLI, the VS Code and JetBrains extensions, and the desktop app. The `manual` alias requires Claude Code v2.1.200 or later. `auto` is ignored when set in project or local settings, so a repository can’t grant itself auto mode; set it in `~/.claude/settings.json` instead. Before v2.1.142, project settings could set `auto`. The `--permission-mode` CLI flag overrides this setting for a single session| `"acceptEdits"` `disableAutoMode`| Set to `"disable"` to prevent [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) from being activated. Equivalent to the top-level `disableAutoMode` setting, which describes the full effect. Most useful in [managed settings](</docs/en/permissions#managed-settings>) where users cannot override it| `"disable"` -`disableBypassPermissionsMode`| Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. Typically placed in [managed settings](</docs/en/permissions#managed-settings>) to enforce organizational policy, but works from any scope| `"disable"` +`disableBypassPermissionsMode`| Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag, and Claude Code ignores an [agent definition’s](</docs/en/sub-agents#permission-modes>) `permissionMode: bypassPermissions`, so the subagent runs with the parent session’s mode. Before v2.1.223, Claude Code applied the frontmatter mode even with bypass disabled. Typically placed in [managed settings](</docs/en/permissions#managed-settings>) to enforce organizational policy, but works from any scope| `"disable"` `skipDangerousModePermissionPrompt`| Skip the confirmation prompt shown before entering bypass permissions mode via `--dangerously-skip-permissions` or `defaultMode: "bypassPermissions"`. Ignored when set in project settings (`.claude/settings.json`) to prevent untrusted repositories from auto-bypassing the prompt| `true` ### @@ -478,7 +478,12 @@ `~/`| Relative to home directory| `~/.kube` becomes `$HOME/.kube` `./` or no prefix| Relative to the project root for project settings, or to `~/.claude` for user settings| `./output` in `.claude/settings.json` resolves to `<project-root>/output` -The older `//path` prefix for absolute paths still works. If you previously used single-slash `/path` expecting project-relative resolution, switch to `./path`. This syntax differs from [Read and Edit permission rules](</docs/en/permissions#read-and-edit>), which use `//path` for absolute and `/path` for project-relative. Sandbox filesystem paths use standard conventions: `/tmp/build` is an absolute path. **Configuration example:** +The older `//path` prefix for absolute paths still works. If you previously used single-slash `/path` expecting project-relative resolution, switch to `./path`. Claude Code strips a trailing slash from a directory path, so `~/.aws` and `~/.aws/` match the same directory. Before v2.1.224, Claude Code passed the trailing slash through to the sandbox, and a `denyRead` or `denyWrite` entry written with one didn’t block its path. Claude Code also removes a trailing `/**`, so `~/build/**` and `~/build` cover the same directory. For the four `filesystem` lists, whether a wildcard such as `*` works depends on which list the entry is in and on the platform: + + * **`allowWrite` and `denyWrite`**: on macOS, wildcards work. On Linux and WSL2, the sandbox mounts concrete paths, so Claude Code skips an entry that contains `*`, `?`, or `[` once the trailing `/**` is removed, and that entry has no effect. Claude Code adds the paths from your `Edit` permission rules to these lists, so the same limit applies to them, and the **Config** tab of `/sandbox` lists the `Edit` rules Claude Code skipped. + * **`denyRead` and `allowRead`**: wildcards work on every platform. On Linux and WSL2, Claude Code expands a read entry to the concrete paths it matches, which it doesn’t do for the write lists. + +This syntax differs from [Read and Edit permission rules](</docs/en/permissions#read-and-edit>), which use `//path` for absolute and `/path` for project-relative. Sandbox filesystem paths use standard conventions: `/tmp/build` is an absolute path. **Configuration example:** { "sandbox": { @@ -503,7 +508,7 @@ **Filesystem and network restrictions** can be configured in two ways that are merged together: * **`sandbox.filesystem` settings** (shown above): Control paths at the OS-level sandbox boundary, or set `filesystem.disabled` to `true` to turn that layer off entirely. These restrictions apply to all subprocess commands (e.g., `kubectl`, `terraform`, `npm`), not just Claude’s file tools. - * **Permission rules** : Use `Edit` allow/deny rules to control Claude’s file tool access, `Read` deny rules to block reads (a `Read` deny rule also blocks the Edit tool on the matching paths), and `WebFetch` allow/deny rules to control network domains. Paths from these rules are also merged into the sandbox configuration. + * **Permission rules** : Use `Edit` allow/deny rules to control Claude’s file tool access, `Read` deny rules to block reads (a `Read` deny rule also blocks the Edit and Write tools on the matching paths), and `WebFetch` allow/deny rules to control network domains. Paths from these rules are also merged into the sandbox configuration. ### @@ -754,7 +759,7 @@ } } -This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns are excluded from file discovery and search results, and read operations on these files are denied. +This replaces the deprecated `ignorePatterns` configuration. Claude Code excludes files matching these patterns from file discovery and search results, denies read operations on them, and blocks the [Edit and Write tools](</docs/en/permissions#read-and-edit>) on the matching paths. ## @@ -927,23 +932,24 @@ * Only available in managed settings (`managed-settings.json`) * Cannot be overridden by user or project settings (highest precedence) * Enforced before network and filesystem operations, so blocked sources never run - * Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern` and `pathPattern`, which use regex matching + * Uses exact matching for most source specifications, including `ref` and `path` for git sources. `hostPattern` and `pathPattern` entries use regex matching. `github` entries with an owner-wildcard `repo` such as `"acme-corp/*"` follow their own matching rules. See Owner wildcards **Allowlist behavior** : * `undefined` (default): no restrictions, so users can add any marketplace * Empty array `[]`: complete lockdown that blocks every marketplace source, including the official Anthropic marketplace, so users can’t add any new marketplaces - * List of sources: users can only add marketplaces that match exactly - -**All supported source types** : The allowlist supports multiple marketplace source types. Most sources use exact matching, while `hostPattern` and `pathPattern` use regex matching against the marketplace host and filesystem path respectively. + * List of sources: users can only add marketplaces that match an entry in the list + +**All supported source types** : The allowlist supports multiple marketplace source types. Most sources use exact matching. `hostPattern` and `pathPattern` use regex matching against the marketplace host and filesystem path respectively, and `github` entries can use an owner wildcard. 1. **GitHub repositories** : { "source": "github", "repo": "acme-corp/approved-plugins" } { "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" } { "source": "github", "repo": "acme-corp/plugins", "ref": "main", "path": "marketplace" } - -Fields: `repo` (required), `ref` (optional: branch or tag), `path` (optional: subdirectory) + { "source": "github", "repo": "acme-corp/*" } + +Fields: `repo` (required), `ref` (optional: branch or tag), `path` (optional: subdirectory) The `"acme-corp/*"` form is an owner wildcard that matches every repository under that GitHub owner. Owner wildcards require Claude Code v2.1.223 or later. Claude Code accepts them only in `strictKnownMarketplaces` and `blockedMarketplaces`. Everywhere else a `github` source appears, such as `extraKnownMarketplaces` or `/plugin marketplace add`, the `repo` value must name a single repository. For the matching rules, see Owner wildcards. 2. **Git repositories** : @@ -1030,7 +1036,7 @@ "strictKnownMarketplaces": [] } -Example: allow only the official Anthropic marketplace. Matching is exact, so this entry doesn’t cover `ref` or `path` variants of the same repository: +Example: allow only the official Anthropic marketplace. Claude Code matches a single-repository entry exactly, so this entry doesn’t cover `ref` or `path` variants of the same repository: { "strictKnownMarketplaces": [ @@ -1057,7 +1063,7 @@ ] } -**Exact matching requirements** : Marketplace sources must match exactly for a user’s addition to be allowed. For git-based sources (`github` and `git`), this includes all optional fields: +**Exact matching requirements** : For most source types, Claude Code allows a user’s addition only when the marketplace source matches an entry exactly. The exceptions are owner-wildcard `github` entries and the regex-matched `hostPattern` and `pathPattern` entries. For the git-based sources `github` and `git`, exact matching includes all optional fields: * The `repo` or `url` must match exactly * The `ref` field must match exactly (or both be undefined) @@ -1067,6 +1073,23 @@ * `{ "source": "github", "repo": "acme-corp/plugins" }` and `{ "source": "github", "repo": "acme-corp/plugins", "ref": "main" }` * `{ "source": "github", "repo": "acme-corp/plugins", "path": "marketplace" }` and `{ "source": "github", "repo": "acme-corp/plugins" }` + +**Owner wildcards** : A `github` entry whose `repo` value is `"<owner>/*"` matches every repository under that GitHub owner. Owner wildcards require Claude Code v2.1.223 or later. Before v2.1.223, Claude Code compared the entry literally, so an allowlist entry matched no repository and a blocklist entry blocked nothing. Single-repository entries are enforced on every version. This entry allows any marketplace repository in the `acme-corp` organization: + + { + "strictKnownMarketplaces": [ + { "source": "github", "repo": "acme-corp/*" } + ] + } + +Only the whole repository-name position can be a wildcard. Claude Code compares entries such as `*`, `*/plugins`, or `acme-corp/tools-*` literally, so they match no repository. The matching rules differ between the two settings: + +Rule| `strictKnownMarketplaces`| `blockedMarketplaces` +---|---|--- +Matching source spellings| `owner/repo` form only. A git URL that clones the same repository doesn’t match| Any spelling, including git URLs that resolve to the same github.com repository +Owner case| Case-sensitive, like exact-entry matching| Case-insensitive +`ref`| Follows the exact-entry rules: an entry with a `ref` matches only sources with that exact ref, and an entry without one matches only sources that don’t specify a ref| An entry without a `ref` blocks all refs of the repositories it matches +`path`| Looser than the exact-entry rules: an entry with a `path` requires that exact value, while an entry without one matches any path inside the repository| An entry without a `path` blocks all paths of the repositories it matches **Comparison with`extraKnownMarketplaces`**:
modified Claude Code in Slack View current →
--- a/slack.md +++ b/slack.md @@ -194,14 +194,7 @@ Channel-based access control -Claude is not automatically added to any channels after installation. Users must explicitly invite Claude to channels where they want to use it: - - * **Invite required** : Type `/invite @Claude` in any channel to add Claude to that channel - * **Channel membership controls access** : Claude can only respond to @mentions in channels where it has been added - * **Access gating through channels** : Admins can control who uses Claude Code by managing which channels Claude is invited to and who has access to those channels - * **Private channel support** : Claude works in both public and private channels, giving teams flexibility in controlling visibility - -This channel-based model allows teams to restrict Claude Code usage to specific channels, providing an additional layer of access control beyond workspace-level permissions. +Installing the app doesn’t add Claude to any channels. Claude responds to @mentions only in channels where it has been added; invite it with `/invite @Claude`. It works in both public and private channels. Admins can control who uses Claude Code by managing which channels Claude is invited to and who has access to those channels. This adds a layer of access control beyond workspace-level permissions. ## @@ -209,7 +202,7 @@ What’s accessible where -**In Slack** : You’ll see status updates, completion summaries, and action buttons. The full transcript is preserved and always accessible. **On the web** : The complete Claude Code session with full conversation history, all code changes, file operations, and the ability to continue the session or create pull requests. For Enterprise and Team accounts, sessions created from Claude in Slack are automatically visible to the organization. See [Claude Code on the Web sharing](</docs/en/claude-code-on-the-web#share-sessions>) for more details. +**In Slack** : You’ll see status updates, completion summaries, and action buttons. The full transcript is preserved and always accessible. **On the web** : The complete Claude Code session with full conversation history, all code changes, and file operations. Sessions stay in your Claude Code history at [claude.ai/code](<https://claude.ai/code>), where you can continue past sessions, reference them, or create pull requests. For Enterprise and Team accounts, sessions created from Claude in Slack are automatically visible to the organization. See [Claude Code on the Web sharing](</docs/en/claude-code-on-the-web#share-sessions>) for more details. ## @@ -302,25 +295,15 @@ 2. Ensure you’re signed into the correct Claude account in your browser 3. Check that your Claude plan includes Claude Code access -### - -​ - -Session expiration - - 1. Sessions remain accessible in your Claude Code history on the web - 2. You can continue or reference past sessions from [claude.ai/code](<https://claude.ai/code>) - ## ​ Current limitations - * **GitHub only** : Currently supports repositories on GitHub. - * **One PR at a time** : Each session can create one pull request. - * **Rate limits apply** : Sessions use your individual Claude plan’s rate limits. - * **Web access required** : Users must have Claude Code on the web access; those without it will only get standard Claude chat responses. + * **GitHub only** : repositories must be on GitHub. + * **One PR at a time** : each session can create one pull request. + * **Web access required** : users need access to Claude Code on the web; without it, Claude replies with standard chat responses. ##
modified Customize your status line View current →
--- a/statusline.md +++ b/statusline.md @@ -132,7 +132,7 @@ * Vim mode toggles * A `refreshInterval` timer elapses, if you set one -Before v2.1.216, resuming a session ran the command twice in quick succession, so the first result could flicker before being replaced. Claude Code debounces updates at 300ms, so rapid changes batch together and your script runs once after the changes stop. 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** +Claude Code debounces updates at 300ms, so rapid changes batch together and your script runs once after the changes stop. 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** * **Multiple lines** : each `echo` or `print` statement displays as a separate row. See the multi-line example. * **Colors** : use [ANSI escape codes](<https://en.wikipedia.org/wiki/ANSI_escape_code#Colors>) like `\033[32m` for green (terminal must support them). See the git status example. @@ -550,7 +550,7 @@ Display multiple lines -Your script can output multiple lines to create a richer display. Each `echo` statement produces a separate row in the status area. +Your script can output multiple lines to create a richer display. This example combines several techniques: threshold-based colors (green under 70%, yellow 70-89%, red 90%+), a progress bar, and git branch info. Each `print` or `echo` statement creates a separate row: @@ -655,7 +655,7 @@ Clickable links -This example creates a clickable link to your GitHub repository. It reads the git remote URL, converts SSH format to HTTPS with `sed`, and wraps the repo name in OSC 8 escape codes. Hold Cmd (macOS) or Ctrl (Windows/Linux) and click to open the link in your browser. +This example creates a clickable link to your GitHub repository. Hold Cmd (macOS) or Ctrl (Windows/Linux) and click to open the link in your browser. Each script gets the git remote URL, converts SSH format to HTTPS, and wraps the repo name in OSC 8 escape codes. The Bash version uses `printf '%b'` which interprets backslash escapes more reliably than `echo -e` across different shells:
modified Create custom subagents View current →
--- a/sub-agents.md +++ b/sub-agents.md @@ -211,7 +211,12 @@ You are a code reviewer. When invoked, analyze the code and provide specific, actionable feedback on quality, security, and best practices. -The frontmatter defines the subagent’s metadata and configuration. The body becomes the system prompt that guides the subagent’s behavior. Subagents receive only this system prompt plus basic environment details like the working directory, not the full Claude Code system prompt. In [non-interactive mode](</docs/en/headless>), the [`--append-subagent-system-prompt`](</docs/en/cli-reference#cli-flags>) flag appends the text you provide to the end of every subagent’s system prompt, including nested subagents. Requires Claude Code v2.1.205 or later. A subagent starts in the main conversation’s current working directory. Within a subagent, `cd` commands don’t persist between Bash or PowerShell tool calls and don’t affect the main conversation’s working directory. To give the subagent an isolated copy of the repository instead, set `isolation: worktree`. A subagent with `isolation: worktree` runs its Bash and PowerShell commands inside its worktree. A command whose working directory resolves to your main checkout instead, for example because the worktree directory was removed while the subagent was running, fails with an error. Before v2.1.203, such a command could run in the main checkout. This working-directory check covers the whole repository containing the directory you launched Claude Code from. When your session runs in a linked [worktree](</docs/en/worktrees>) of its own, the check also covers the main checkout that worktree is linked from. Before v2.1.210, the check covered only the launch directory itself. A command whose working directory resolved elsewhere in the same repository, such as the repository root when you launched Claude Code from a monorepo subdirectory, ran there instead of failing. For Bash commands, Claude Code also checks the command itself and blocks one that redirects git into the main checkout; the redirect vectors and the too-complex-to-check rule are listed under [How Claude Code enforces isolation](</docs/en/worktrees#how-claude-code-enforces-isolation>). PowerShell commands get only the working-directory check. [Monitor](</docs/en/tools-reference#monitor-tool>) commands go through the same working-directory and command-content checks as Bash commands. When the main conversation itself runs isolated in a worktree, Claude Code applies the same checks to the session and to every subagent it spawns, including subagents without `isolation: worktree`; see [How Claude Code enforces isolation](</docs/en/worktrees#how-claude-code-enforces-isolation>). +The frontmatter defines the subagent’s metadata and configuration. The body becomes the system prompt that guides the subagent’s behavior. Subagents receive only this system prompt plus basic environment details like the working directory, not the full Claude Code system prompt. In [non-interactive mode](</docs/en/headless>), the [`--append-subagent-system-prompt`](</docs/en/cli-reference#cli-flags>) flag appends the text you provide to the end of every subagent’s system prompt, including nested subagents. Requires Claude Code v2.1.205 or later. A subagent starts in the main conversation’s current working directory. Within a subagent, `cd` commands don’t persist between Bash or PowerShell tool calls and don’t affect the main conversation’s working directory. To give the subagent an isolated copy of the repository instead, set `isolation: worktree`. A subagent with `isolation: worktree` runs its Bash and PowerShell commands inside its worktree. A command whose working directory resolves to your main checkout instead, for example because the worktree directory was removed while the subagent was running, fails with an error. Before v2.1.203, such a command could run in the main checkout. This working-directory check covers the whole repository containing the directory you launched Claude Code from. When your session runs in a linked [worktree](</docs/en/worktrees>) of its own, the check also covers the main checkout that worktree is linked from. Before v2.1.210, the check covered only the launch directory itself. A command whose working directory resolved elsewhere in the same repository, such as the repository root when you launched Claude Code from a monorepo subdirectory, ran there instead of failing. For Bash commands, Claude Code also checks the command itself in two ways: + + * It blocks a command that redirects git into the main checkout. + * It refuses a command whose shape it can’t verify stays inside the worktree. This refusal applies even to a command that runs no git. + +The redirect vectors and the shape rules are listed under [How Claude Code enforces isolation](</docs/en/worktrees#how-claude-code-enforces-isolation>). PowerShell commands get only the working-directory check. [Monitor](</docs/en/tools-reference#monitor-tool>) commands go through the same working-directory and command-content checks as Bash commands. When the main conversation itself runs isolated in a worktree, Claude Code applies the same checks to the session and to every subagent it spawns, including subagents without `isolation: worktree`; see [How Claude Code enforces isolation](</docs/en/worktrees#how-claude-code-enforces-isolation>). #### @@ -260,7 +265,12 @@ 3. The subagent definition’s `model` frontmatter 4. The main conversation’s model -As of v2.1.196, setting `CLAUDE_CODE_SUBAGENT_MODEL` to `inherit` is the same as leaving it unset: resolution continues with the per-invocation `model` parameter, then the frontmatter. In earlier versions, `inherit` forced subagents onto the main conversation’s model and ignored both of those sources. Claude Code checks the environment variable, per-invocation parameter, and frontmatter values against your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist. When a blocked value is a family alias such as `opus`, Claude Code runs the subagent on the newest version of that family the allowlist permits, following the same [substitution rules and provider scope](</docs/en/model-config#restrict-model-selection>) as `/model`. For any other blocked value, on providers where that substitution doesn’t operate, or when the allowlist permits no version of the family, Claude Code runs the subagent on the inherited model instead. Before v2.1.222, Claude Code ran the subagent on the inherited model for a blocked family alias as well. A per-invocation `model` parameter also applies when the subagent is resumed or sent a follow-up message, so the subagent stays on that model. Before v2.1.211, resuming dropped the per-invocation value and the subagent reverted to its definition’s `model` field or, without one, the main conversation’s model. As of v2.1.198, subagents also inherit the main conversation’s [extended thinking](</docs/en/model-config#extended-thinking>) configuration: if thinking is on in your session, it’s on for the subagent, and if it’s off, it stays off. There is no per-subagent thinking setting. Before v2.1.198, subagents ran with extended thinking disabled regardless of the main conversation’s setting. +As of v2.1.196, setting `CLAUDE_CODE_SUBAGENT_MODEL` to `inherit` is the same as leaving it unset: resolution continues with the per-invocation `model` parameter, then the frontmatter. In earlier versions, `inherit` forced subagents onto the main conversation’s model and ignored both of those sources. Claude Code checks the environment variable, per-invocation parameter, and frontmatter values against your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist. For a blocked value, it substitutes another model: + + * When the blocked value is a family alias such as `opus`, Claude Code runs the subagent on the newest version of that family the allowlist permits, following the same [substitution rules and provider scope](</docs/en/model-config#restrict-model-selection>) as `/model`. Before v2.1.222, Claude Code ran the subagent on the inherited model for a blocked family alias as well. + * For any other blocked value, on providers where that substitution doesn’t operate, or when the allowlist permits no version of the family, Claude Code runs the subagent on the inherited model instead. + +In interactive sessions, Claude Code shows a warning naming the requested model and the model the subagent runs on, for either substitution. A per-invocation `model` parameter also applies when the subagent is resumed or sent a follow-up message, so the subagent stays on that model. Before v2.1.211, resuming dropped the per-invocation value and the subagent reverted to its definition’s `model` field or, without one, the main conversation’s model. As of v2.1.198, subagents also inherit the main conversation’s [extended thinking](</docs/en/model-config#extended-thinking>) configuration: if thinking is on in your session, it’s on for the subagent, and if it’s off, it stays off. There is no per-subagent thinking setting. Before v2.1.198, subagents ran with extended thinking disabled regardless of the main conversation’s setting. ### @@ -380,7 +390,7 @@ Permission modes -The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation and can override the mode, except when the parent mode takes precedence as described below. +The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation and can override the mode, except in the cases described below. Mode| Behavior ---|--- @@ -401,7 +411,7 @@ See [permission modes](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) for details. -If the parent uses `bypassPermissions` or `acceptEdits`, this takes precedence and can’t be overridden. If the parent uses [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), the subagent inherits auto mode and any `permissionMode` in its frontmatter is ignored: the classifier evaluates the subagent’s tool calls with the same block and allow rules as the parent session. +If the parent uses `bypassPermissions` or `acceptEdits`, this takes precedence and can’t be overridden. If the parent uses [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), the subagent inherits auto mode and any `permissionMode` in its frontmatter is ignored: the classifier evaluates the subagent’s tool calls with the same block and allow rules as the parent session. If bypass mode is disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>), Claude Code ignores `permissionMode: bypassPermissions` in the frontmatter and the subagent runs with the parent session’s mode. Before v2.1.223, Claude Code applied the frontmatter mode even with bypass disabled. #### @@ -421,7 +431,7 @@ Implement API endpoints. Follow the conventions and patterns from the preloaded skills. -The full content of each listed skill is injected into the subagent’s context at startup. This field controls which skills are preloaded, not which skills the subagent can access: without it, the subagent can still discover and invoke project, user, and plugin skills through the Skill tool during execution. To prevent a subagent from invoking skills entirely, omit `Skill` from the `tools` list or add it to `disallowedTools`. You can’t preload skills that set [`disable-model-invocation: true`](</docs/en/skills#control-who-invokes-a-skill>), since preloading draws from the same set of skills Claude can invoke. This includes the bundled `/verify` and `/code-review` skills: only you can run them, so they can’t be preloaded either. If a listed skill is missing or disabled, Claude Code skips it and logs a warning to the debug log. +The full content of each listed skill is injected into the subagent’s context at startup. This field controls which skills are preloaded, not which skills the subagent can access: without it, the subagent can still discover and invoke project, user, and plugin skills through the Skill tool during execution. To prevent a subagent from invoking skills entirely, omit `Skill` from the `tools` list or add it to `disallowedTools`. You can’t preload skills that set [`disable-model-invocation: true`](</docs/en/skills#control-who-invokes-a-skill>), since preloading draws from the same set of skills Claude can invoke. This includes the bundled `/verify` skill: only you can run it, so it can’t be preloaded either. If a listed skill is missing or disabled, for example by your organization’s policy, Claude Code skips it and logs a warning to the debug log. This is the inverse of [running a skill in a subagent](</docs/en/skills#run-skills-in-a-subagent>). With `skills` in a subagent, the subagent controls the system prompt and loads skill content. With `context: fork` in a skill, the skill content is injected into the agent you specify. Both use the same underlying system. @@ -780,7 +790,7 @@ * You want to enforce specific tool restrictions or permissions * The work is self-contained and can return a summary -Consider [Skills](</docs/en/skills>) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context. For a quick question about something already in your conversation, use [`/btw`](</docs/en/interactive-mode#side-questions-with-%2Fbtw>) instead of a subagent. It sees your full context but has no tool access, and the answer is discarded rather than added to history. +Consider [Skills](</docs/en/skills>) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context. For a question about something already in your conversation, use [`/btw`](</docs/en/interactive-mode#side-questions-with-%2Fbtw>) instead of a subagent. It sees your full context but has no tool access, and the answer isn’t added to history. ### @@ -849,7 +859,7 @@ Resume subagents -Each subagent invocation creates a new instance with fresh context. To continue an existing subagent’s work instead of starting over, ask Claude to resume it. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, Claude receives its agent ID. The built-in Explore and Plan agents are one-shot and return no agent ID, so they can’t be resumed; use `general-purpose` or a custom subagent when you need to continue the work. Claude uses the `SendMessage` tool with the agent’s ID 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, the same tool can 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 with fresh context. To continue an existing subagent’s work instead of starting over, ask Claude to resume it. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, Claude receives its agent ID. The built-in Explore and Plan agents are one-shot and return no agent ID, so they can’t be resumed; use `general-purpose` or a custom subagent when you need to continue the work. Claude uses the `SendMessage` tool with the agent’s ID or name as the `to` field to resume it. `SendMessage` doesn’t require [agent teams](</docs/en/agent-teams>) to be enabled; only structured team-protocol messages such as `shutdown_request` and `plan_approval_response` do. 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] @@ -861,7 +871,7 @@ * **Main conversation compaction** : when the main conversation compacts, subagent transcripts are unaffected. They’re stored in separate files. * **Session persistence** : subagent transcripts persist within their session. You can resume a subagent after restarting Claude Code by resuming the same session. - * **Automatic cleanup** : Claude Code deletes subagent transcripts after the `cleanupPeriodDays` retention period, 30 days by default. + * **Automatic cleanup** : Claude Code deletes subagent transcripts after the `cleanupPeriodDays` retention period, 30 days by default, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). ####
modified Configure your terminal for Claude Code View current →
--- a/terminal-config.md +++ b/terminal-config.md @@ -291,7 +291,7 @@ Switch to fullscreen rendering -In [screen reader mode](</docs/en/accessibility>), this section doesn’t apply. Claude Code always renders as plain scrolling text except in attached [background sessions](</docs/en/agent-view>), and if you run `/tui fullscreen` in any other session, Claude Code prints an explanation instead of switching. If the display flickers or the scroll position jumps while Claude is working, switch to [fullscreen rendering mode](</docs/en/fullscreen>). It draws to a separate screen the terminal reserves for full-screen apps instead of appending to your normal scrollback, which keeps memory usage flat and adds mouse support for scrolling and selection. In this mode you scroll with the mouse or PageUp inside Claude Code rather than with your terminal’s native scrollback; see the [fullscreen page](</docs/en/fullscreen#search-and-review-the-conversation>) for how to search and copy. If flicker is the only problem and your terminal supports synchronized output but isn’t auto-detected, such as Emacs `eat`, set [`CLAUDE_CODE_FORCE_SYNC_OUTPUT=1`](</docs/en/env-vars>) to stop the flicker without changing renderers. Run `/tui fullscreen` to switch and save the preference. Your conversation relaunches intact and future sessions start in fullscreen. You can also set the `CLAUDE_CODE_NO_FLICKER` environment variable before starting Claude Code: +In [screen reader mode](</docs/en/accessibility>), this section doesn’t apply. Claude Code always renders as plain scrolling text except in attached [background sessions](</docs/en/agent-view>), and if you run `/tui fullscreen` in any other session, Claude Code prints an explanation instead of switching. If the display flickers or the scroll position jumps while Claude is working, switch to [fullscreen rendering mode](</docs/en/fullscreen>). In this mode you scroll with the mouse or PageUp inside Claude Code rather than with your terminal’s native scrollback; see the [fullscreen page](</docs/en/fullscreen#search-and-review-the-conversation>) for how to search and copy. If flicker is the only problem and your terminal supports synchronized output but isn’t auto-detected, such as Emacs `eat`, set [`CLAUDE_CODE_FORCE_SYNC_OUTPUT=1`](</docs/en/env-vars>) to stop the flicker without changing renderers. Run `/tui fullscreen` to switch and save the preference. Your conversation relaunches intact and future sessions start in fullscreen. You can also set the `CLAUDE_CODE_NO_FLICKER` environment variable before starting Claude Code: Bash and Zsh @@ -315,7 +315,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 cache file ages past `cleanupPeriodDays`. Claude Code deletes cache files older than [`cleanupPeriodDays`](</docs/en/settings#available-settings>) at startup, 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. 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#available-settings>), 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 Enterprise deployment overview View current →
Show diff (117 lines)
--- a/third-party-integrations.md +++ b/third-party-integrations.md @@ -40,104 +40,7 @@ * **Corporate proxy** : Routes traffic through an HTTP/HTTPS proxy. Use this if your organization requires all outbound traffic to pass through a proxy server for security monitoring, compliance, or network policy enforcement. Configure with the `HTTPS_PROXY` or `HTTP_PROXY` environment variables. Learn more in [Enterprise network configuration](</docs/en/network-config>). * **LLM Gateway** : A service that sits between Claude Code and the cloud provider to handle authentication and routing. Use this if you need centralized usage tracking across teams, custom rate limiting or budgets, or centralized authentication management. Configure with the `ANTHROPIC_BASE_URL`, `ANTHROPIC_BEDROCK_BASE_URL`, `ANTHROPIC_AWS_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL`, or `ANTHROPIC_FOUNDRY_BASE_URL` environment variables. Learn more in [LLM gateways](</docs/en/llm-gateway>). -The following examples show the environment variables to set in your shell or shell profile (`.bashrc`, `.zshrc`). See [Settings](</docs/en/settings>) for other configuration methods. - -### - -​ - -Amazon Bedrock - - * Corporate proxy - - * LLM Gateway - -Route Amazon Bedrock traffic through your corporate proxy by setting the following [environment variables](</docs/en/env-vars>): - - # Enable Bedrock - export CLAUDE_CODE_USE_BEDROCK=1 - export AWS_REGION=us-east-1 - - # Configure corporate proxy - export HTTPS_PROXY='https://proxy.example.com:8080' - -Route Amazon Bedrock traffic through your LLM gateway by setting the following [environment variables](</docs/en/env-vars>): - - # Enable Bedrock - export CLAUDE_CODE_USE_BEDROCK=1 - - # Configure LLM gateway - export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock' - export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # If gateway handles AWS auth - -### - -​ - -Microsoft Foundry - - * Corporate proxy - - * LLM Gateway - -Route Microsoft Foundry traffic through your corporate proxy by setting the following [environment variables](</docs/en/env-vars>): - - # Enable Microsoft Foundry - export CLAUDE_CODE_USE_FOUNDRY=1 - export ANTHROPIC_FOUNDRY_RESOURCE=your-resource - export ANTHROPIC_FOUNDRY_API_KEY=your-api-key # Or omit for Entra ID auth - - # Configure corporate proxy - export HTTPS_PROXY='https://proxy.example.com:8080' - -Route Microsoft Foundry traffic through your LLM gateway by setting the following [environment variables](</docs/en/env-vars>): - - # Enable Microsoft Foundry - export CLAUDE_CODE_USE_FOUNDRY=1 - - # Configure LLM gateway - export ANTHROPIC_FOUNDRY_BASE_URL='https://your-llm-gateway.com' - export ANTHROPIC_FOUNDRY_API_KEY=your-gateway-key # Sent as x-api-key - -### - -​ - -Google Cloud’s Agent Platform - - * Corporate proxy - - * LLM Gateway - -Route Google Cloud’s Agent Platform traffic through your corporate proxy by setting the following [environment variables](</docs/en/env-vars>): - - # Enable Agent Platform - export CLAUDE_CODE_USE_VERTEX=1 - export CLOUD_ML_REGION=us-east5 - export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id - - # Configure corporate proxy - export HTTPS_PROXY='https://proxy.example.com:8080' - -Route Google Cloud’s Agent Platform traffic through your LLM gateway by setting the following [environment variables](</docs/en/env-vars>): - - # Enable Agent Platform - export CLAUDE_CODE_USE_VERTEX=1 - - # Configure LLM gateway - export ANTHROPIC_VERTEX_BASE_URL='https://your-llm-gateway.com/vertex' - export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 # If gateway handles GCP auth - export ANTHROPIC_VERTEX_PROJECT_ID=your-gcp-project-id - export CLOUD_ML_REGION=us-east5 - -Use `/status` in Claude Code to verify your proxy and gateway configuration is applied correctly. For example, with the Bedrock gateway configuration above, the output includes lines like: - - API provider: Amazon Bedrock - Bedrock base URL: https://your-llm-gateway.com/bedrock - AWS region: us-east-1 - AWS auth skipped - -If you configured a corporate proxy, `/status` also shows a `Proxy` line with your proxy URL. +For the per-provider environment variables that route Amazon Bedrock, Microsoft Foundry, or Google Cloud’s Agent Platform through an LLM gateway, see [route to a cloud provider through a gateway](</docs/en/llm-gateway-connect#route-to-a-cloud-provider-through-a-gateway>). Run `/status` in Claude Code to verify which provider, base URL, and proxy a session is using. ## @@ -196,7 +99,7 @@ Leverage MCP for integrations -MCP is a great way to give Claude Code more information, such as connecting to ticket management systems or error logs. We recommend that one central team configures MCP servers and checks a `.mcp.json` configuration into the codebase so that all users benefit. [Learn more](</docs/en/mcp>). At Anthropic, we trust Claude Code to power development across every Anthropic codebase. We hope you enjoy using Claude Code as much as we do. +MCP is a great way to give Claude Code more information, such as connecting to ticket management systems or error logs. We recommend that one central team configures MCP servers and checks a `.mcp.json` configuration into the codebase so that all users benefit. [Learn more](</docs/en/mcp>). ##
modified Scale to many tools with tool search View current →
--- a/tool-search.md +++ b/tool-search.md @@ -2,8 +2,6 @@ * **Context efficiency:** Tool definitions can consume large portions of the context window (50 tools can use 10-20K tokens), leaving less room for actual work. * **Tool selection accuracy:** Tool selection accuracy degrades with more than 30-50 tools loaded at once. - -Tool search is enabled by default. ## @@ -11,7 +9,7 @@ How tool search works -When tool search is active, tool definitions are withheld from the context window. The agent receives a summary of available tools and searches for relevant ones when the task requires a capability not already loaded. Up to five of the most relevant tools are loaded into context by default, where they stay available for subsequent turns. If the conversation is long enough that the SDK compacts earlier messages to free space, previously discovered tools may be removed, and the agent searches again as needed. Tool search adds one extra round-trip the first time Claude discovers a tool (the search step), but for large tool sets this is offset by smaller context on every turn. With fewer than ~10 tools, loading everything upfront is typically faster. For details on the underlying API mechanism, see [Tool search in the API](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool>). +Tool search is on by default, with the exceptions listed in Configure tool search. When it is active, tool definitions are withheld from the context window. The agent receives a summary of available tools and searches for relevant ones when the task requires a capability not already loaded. Up to five of the most relevant tools are loaded into context by default, where they stay available for subsequent turns. If the conversation is long enough that the SDK compacts earlier messages to free space, previously discovered tools may be removed, and the agent searches again as needed. Tool search adds one extra round-trip the first time Claude discovers a tool (the search step), but for large tool sets this is offset by smaller context on every turn. With fewer than ~10 tools whose definitions fit comfortably in the context window, loading everything upfront is typically faster. For details on the underlying API mechanism, see [Tool search in the API](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool>). Tool search isn’t supported on Microsoft Foundry [deployments hosted on Azure](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>), which reject it server-side: the SDK detects the rejection and loads tool definitions upfront for that deployment instead. `ENABLE_TOOL_SEARCH` can’t override this, since the rejection comes from the deployment itself. @@ -36,7 +34,7 @@ `auto:N`| Same as `auto` with a custom percentage. `auto:5` activates when tool definitions exceed 5% of the context window. Lower values activate sooner. `false`| Tool search is off. All tool definitions are loaded into context on every turn. -Setting [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`](</docs/en/env-vars>) keeps tool search off, and `ENABLE_TOOL_SEARCH` can’t override it. The variable strips the beta header that `defer_loading` tool definitions and `tool_reference` content blocks require. Tool search applies to all registered tools, whether they come from remote MCP servers or [custom SDK MCP servers](</docs/en/agent-sdk/custom-tools>). When using `auto`, the threshold is based on the combined size of all tool definitions across all servers. Set the value in the `env` option on `query()`. In TypeScript, `env` replaces the subprocess environment, so spread `...process.env` to keep inherited variables. In Python, `env` is merged on top of the inherited environment. This example connects to a remote MCP server that exposes many tools, pre-approves all of them with a wildcard, and uses `auto:5` so tool search activates when their definitions exceed 5% of the context window: +Setting [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`](</docs/en/env-vars>) keeps tool search off. You can’t override it by setting `ENABLE_TOOL_SEARCH` yourself. Your organization can keep tool search on through [managed settings](</docs/en/settings#settings-files>), on Claude Code v2.1.227 or later. [Disable pre-release capabilities](</docs/en/llm-gateway-protocol#disable-pre-release-capabilities>) covers where the override applies and what the variable strips. Tool search applies to all registered tools, whether they come from remote MCP servers or [custom SDK MCP servers](</docs/en/agent-sdk/custom-tools>). When using `auto`, the threshold is based on the combined size of all tool definitions across all servers. Set the value in the `env` option on `query()`. In TypeScript, `env` replaces the subprocess environment, so spread `...process.env` to keep inherited variables. In Python, `env` is merged on top of the inherited environment. This example connects to a remote MCP server that exposes many tools, pre-approves all of them with a wildcard, and uses `auto:5` so tool search activates when their definitions exceed 5% of the context window: TypeScript
modified Tools reference View current →
--- a/tools-reference.md +++ b/tools-reference.md @@ -19,7 +19,7 @@ `ExitWorktree`| Exits a worktree session and returns to the original directory. Not available to subagents that already run in their own working directory, such as with [`isolation: worktree`](</docs/en/sub-agents#supported-frontmatter-fields>)| No `Glob`| Finds files based on pattern matching. See Glob tool behavior| No `Grep`| Searches for patterns in file contents. See Grep tool behavior| No -`ListAgents`| Lists the agents Claude can message with `SendMessage`, apart from [agent team](</docs/en/agent-teams>) teammates, which Claude reaches through the team’s roster: subagents in the session, your other local Claude Code sessions, your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions when this session has cloud access, and your Remote Control sessions on other machines while this session is connected to [Remote Control](</docs/en/remote-control>). Backs the `/list-agents` command. See [cross-session messaging](</docs/en/cross-session-messaging>). Requires Claude Code v2.1.224 or later, and appears only in sessions where [cross-session messaging is enabled](</docs/en/cross-session-messaging#availability>)| No +`ListAgents`| Lists the agents Claude can message with `SendMessage`, apart from [agent team](</docs/en/agent-teams>) teammates, which Claude reaches through the team’s roster: subagents in the session, your other local Claude Code sessions, and, while this session is connected to [Remote Control](</docs/en/remote-control>), your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions and your Remote Control sessions on other machines. Backs the `/list-agents` command. See [cross-session messaging](</docs/en/cross-session-messaging>). Requires Claude Code v2.1.224 or later, and appears only in sessions where [cross-session messaging is enabled](</docs/en/cross-session-messaging#availability>)| No `ListMcpResourcesTool`| Lists resources exposed by connected [MCP servers](</docs/en/mcp>)| No `LSP`| Code intelligence via language servers: jump to definitions, find references, report type errors and warnings. See LSP tool behavior| No `Monitor`| Runs a command in the background and feeds each output line back to Claude, so it can react to log entries, file changes, or polled status mid-conversation. Can also open a WebSocket and treat each incoming message as an event. See Monitor tool| Yes @@ -28,10 +28,10 @@ `PushNotification`| Sends a desktop notification, and a phone push when [Remote Control](</docs/en/remote-control>) is connected, so a long-running task or [scheduled task](</docs/en/scheduled-tasks>) can reach you when you step away. Push delivery runs through Anthropic-hosted infrastructure, which is not accessible from Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry| No `Read`| Reads the contents of files. See Read tool behavior| No `ReadMcpResourceTool`| Reads a specific MCP resource by URI| No -`RemoteTrigger`| Creates, updates, runs, and lists [Routines](</docs/en/routines>) on claude.ai. Backs the `/schedule` command. Routines live on claude.ai and require a Pro, Max, Team, or Enterprise plan, so this tool is not accessible from Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry| 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| 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| 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| 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| 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 @@ -77,7 +77,7 @@ `WebFetch(domain:example.com)`| WebFetch| [Domain matching](</docs/en/permissions#webfetch>) `WebSearch`| WebSearch| No specifier; allow or deny the tool as a whole -Tools not listed here, such as `ExitPlanMode` or `ShareOnboardingGuide`, accept only the bare tool name with no specifier. An `Edit(...)` allow rule also grants read access to the same path, so you don’t need a matching `Read(...)` rule. A `Read(...)` deny rule also blocks the Edit tool on the same path, including creating a new file there, because editing requires reading the result back. The `Read` deny check on edits requires Claude Code v2.1.208 or later. Hook `matcher` fields use bare tool names, not the parenthesized rule format. See [matcher patterns](</docs/en/hooks#matcher-patterns>) for the matching rules. For the field names each tool passes to `tool_input` in hooks, see the [PreToolUse input reference](</docs/en/hooks#pretooluse-input>). +Tools not listed here, such as `ExitPlanMode` or `ShareOnboardingGuide`, accept only the bare tool name with no specifier. An `Edit(...)` allow rule also grants read access to the same path, so you don’t need a matching `Read(...)` rule. A `Read(...)` deny rule also blocks the Edit and Write tools on the same path, including creating a new file there, because both tools change content Claude has to be able to read back. The `Read` deny check requires Claude Code v2.1.208 or later on edits, and v2.1.228 or later on writes. Hook `matcher` fields use bare tool names, not the parenthesized rule format. See [matcher patterns](</docs/en/hooks#matcher-patterns>) for the matching rules. For the field names each tool passes to `tool_input` in hooks, see the [PreToolUse input reference](</docs/en/hooks#pretooluse-input>). ## @@ -169,7 +169,13 @@ Background commands -For long-running processes such as dev servers or watch builds, Claude can set `run_in_background: true` to start the command as a background task and continue working while it runs. List and stop background tasks with `/tasks`. In non-interactive mode with the `-p` flag, [background tasks end shortly after the run’s final result](</docs/en/headless#background-tasks-at-exit>). When a command reaches its timeout without finishing, Claude Code moves it to the background instead of stopping it, so Claude keeps working while the command runs to completion. Claude Code never auto-backgrounds a command that starts with `sleep`, and setting [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1`](</docs/en/env-vars#variables>) disables auto-backgrounding along with the rest of the background task functionality. The result of a command moved this way states what happened: +For long-running processes such as dev servers or watch builds, Claude can set `run_in_background: true` to start the command as a background task and continue working while it runs. List and stop background tasks with `/tasks`. When a [subagent running in the foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) started the command, Claude Code ends it when that subagent gives its final response. Commands started by the main conversation or by a background subagent keep running. In non-interactive mode with the `-p` flag, [background tasks end shortly after the run’s final result](</docs/en/headless#background-tasks-at-exit>). When a command reaches its timeout without finishing, Claude Code moves it to the background instead of stopping it. Claude keeps working while the command continues. Claude Code applies the same lifetime rules to a moved command as to any other background command, so it still ends a foreground subagent’s command at that subagent’s final response. Setting [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1`](</docs/en/env-vars#variables>) disables auto-backgrounding along with the rest of the background task functionality. Claude Code never auto-backgrounds three kinds of command. It stops them at the timeout instead: + + * A command that starts with `sleep`. + * A command that runs `git` anywhere in it. + * A compound command Claude Code can’t fully parse into simple commands. + +The result of a command moved to the background states what happened: * When the timeout triggers the move, the result reports it explicitly: `Command did not complete within its 120s timeout and was moved to the background`, with the seconds matching the timeout that applied, followed by the task ID and the path of the file the output is being written to. * A `cd`, `pushd`, `popd`, or `chdir` inside a command that is moved to the background never carries over: the result states `Session cwd remains <dir>; directory changes made by the backgrounded command do not apply to subsequent commands.`, so Claude doesn’t act on a directory change that didn’t happen. @@ -354,7 +360,7 @@ * `"shell": "powershell"` on individual [command hooks](</docs/en/hooks#command-hook-fields>): runs that hook in PowerShell. Hooks spawn PowerShell directly, so this works regardless of `CLAUDE_CODE_USE_POWERSHELL_TOOL`. * `shell: powershell` in [skill frontmatter](</docs/en/skills#frontmatter-reference>): runs `!`command`` blocks in PowerShell. Requires the PowerShell tool to be enabled. -The same main-session working-directory reset behavior described under the Bash tool section applies to PowerShell commands, including the `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` environment variable. As of v2.1.196, exit code 1 from `grep`, `egrep`, `fgrep`, and `git grep` means no matches, and exit code 1 from `git diff` means differences exist, so these results aren’t reported to Claude as command failures. +The same main-session working-directory reset behavior described under the Bash tool section applies to PowerShell commands, including the `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` environment variable. As of v2.1.196, exit code 1 from `grep`, `rg`, `egrep`, `fgrep`, `findstr`, and `git grep` means no matches. Exit code 1 from `git diff` means differences exist. Neither result is reported to Claude as a command failure. For `robocopy`, exit codes 0 through 7 are informational results, such as files copied or extra files detected. Exit codes of 8 or higher count as failures. ### @@ -393,7 +399,7 @@ * **Images** : PNG, JPG, and other image formats are returned as visual content that Claude can see, not as raw bytes. Claude Code resizes and recompresses large images to fit the model’s image size limits before sending them, so Claude may see a downscaled version of a large screenshot. As of v2.1.196, an image that is still larger than 500KB after that resize is re-encoded as a JPEG at reduced quality with its pixel dimensions unchanged. If Claude misses fine pixel-level detail in a large image, ask it to crop the region of interest first, for example with ImageMagick via Bash. * **PDFs** : Claude reads short `.pdf` files whole. For PDFs longer than 10 pages, it reads in ranges with a `pages` parameter, such as `"1-5"`, up to 20 pages at a time. - * **Jupyter notebooks** : `.ipynb` files return all cells with their outputs, including code, markdown, and visualizations. + * **Jupyter notebooks** : `.ipynb` files return all cells with their outputs, including code, markdown, and visualizations. Claude Code refuses to read a notebook file over 100 MB; the error tells Claude how to read a portion of the notebook instead, such as a slice of cells, with a shell command. Read only reads files, not directories. Claude lists directory contents with a shell command such as `ls`. @@ -437,7 +443,13 @@ Write tool behavior -The Write tool creates a new file or overwrites an existing one with the full content provided. It doesn’t append or merge. If the target path already exists, Claude must have read that file at least once in the current conversation before overwriting it. A Write to an unread existing file fails with an error. This constraint doesn’t apply to new files. Viewing the file with Bash also satisfies this requirement under the same rules described in Edit tool behavior. For partial changes to an existing file, Claude uses Edit instead of Write. +The Write tool creates a new file or overwrites an existing one with the full content provided. It doesn’t append or merge. Whether Claude must read an existing file in the current conversation before overwriting it depends on the model and the file: + + * Claude Opus 4.6, Claude Haiku 4.5, and older models always require the read, so a Write to an unread existing file fails with an error. + * Newer models can overwrite a file they never read this session under the same conditions as read-before-edit: reading it wouldn’t need a permission prompt and the Read tool is available. + * Jupyter notebooks, and files Claude has read only partially with a `PARTIAL view` notice, require the read on every model. + +This constraint doesn’t apply to new files. Before v2.1.228, every model required the read before overwriting an existing file. Viewing the file with Bash also satisfies this requirement under the same rules described in Edit tool behavior. For partial changes to an existing file, Claude uses Edit instead of Write. ##
modified Agent SDK reference - TypeScript View current →
Show diff (183 lines)
--- a/typescript.md +++ b/typescript.md @@ -512,7 +512,7 @@ `forkSession`| `boolean`| `false`| When resuming with `resume`, fork to a new session ID instead of continuing the original session `forwardSubagentText`| `boolean`| `false`| Forward subagent text and thinking blocks as assistant and user messages with `parent_tool_use_id` set, so consumers can render a nested transcript. By default only `tool_use` and `tool_result` blocks from subagents are emitted. Messages from subagents at every nesting depth are forwarded on Claude Code v2.1.219 and later; before v2.1.219, only messages from depth-1 subagents appeared `hooks`| `Partial<Record<``HookEvent``, ``HookCallbackMatcher``[]>>`| `{}`| Hook callbacks for events -`includeHookEvents`| `boolean`| `false`| Include hook lifecycle events for every hook event 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 +`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#compute-managed-settings-with-a-policy-helper>) is configured. 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 @@ -532,6 +532,7 @@ `plugins`| `SdkPluginConfig``[]`| `[]`| Load custom plugins from local paths. See [Plugins](</docs/en/agent-sdk/plugins>) for details `promptSuggestions`| `boolean`| `false`| Enable prompt suggestions. Emits a `prompt_suggestion` message after each turn with a predicted next user prompt `resume`| `string`| `undefined`| Session ID to resume +`resumeDropsTurn`| `string`| `undefined`| With `resumeSessionAt`: the prompt UUID of the turn the truncating resume intends to discard. Claude Code refuses the resume when the discarded range contains anything not attributable to that turn, such as absorbed queued messages or task notifications, and names the `--resume-drops-turn` flag in the rejection message. Only the Agent SDK and print-mode resumes read the pair. Requires Claude Code v2.1.223 or later `resumeSessionAt`| `string`| `undefined`| Resume session at a specific message UUID `sandbox`| `SandboxSettings`| `undefined`| Configure sandbox behavior programmatically. See Sandbox settings for details `sessionId`| `string`| Auto-generated| Use a specific UUID for the session instead of auto-generating one @@ -1358,6 +1359,9 @@ * `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`. + * `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. * `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. @@ -1377,7 +1381,7 @@ `sdk_opt_in_required`| The session hasn’t opted in to fast mode: pass `fastMode: true` in the `settings` option or through `applyFlagSettings()` `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 a background task finishes and the SDK injects a synthetic follow-up turn, the resulting `SDKResultMessage` carries `origin: { kind: "task-notification" }`. Check this field to distinguish results that answer your prompt from results emitted for background-task follow-ups, so you can route or suppress the latter. The field is absent for results emitted before any user turn, such as startup errors. 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. +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. ### @@ -1462,7 +1466,7 @@ `SDKInformationalMessage` -Generic text banner emitted by the loop. Carries non-error status lines, hook feedback such as a `UserPromptSubmit` hook’s block reason, and command output. Render `content` as plaintext at the given `level`. +Generic text banner emitted by the loop. Carries non-error status lines, hook feedback such as a `UserPromptSubmit` hook’s block reason, and command output. On Claude Code v2.1.227 or later, a hook’s [`systemMessage`](</docs/en/hooks#json-output>) can arrive as this message, with each line prefixed by the hook’s name, such as `PostToolUse:Bash says:`. Whether a hook’s `systemMessage` arrives as this message depends on the event. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says how output surfaces. Render `content` as plaintext at the given `level`. type SDKInformationalMessage = { type: "system"; @@ -1515,7 +1519,13 @@ `SDKPermissionDeniedMessage` -Stream event emitted when the permission system auto-denies a tool call without an interactive prompt. Use it to render the denial in your UI as it happens, rather than only observing the `is_error` tool result that follows. The interactive ask path reaches your application separately through the `canUseTool` callback. Denials issued by a `PreToolUse` hook are not reported through this event. +Stream event emitted when the permission system denies a tool call without an interactive prompt. Use it to render the denial in your UI as it happens, rather than only observing the `is_error` tool result that follows. Which denials it reports depends on how the run handles permission prompts: + + * **With a`canUseTool` callback**: permission prompts go to your callback, and this event reports the denials Claude Code decides on its own without calling it. + * **With neither** : a bare `-p` run, or `query()` that sets neither `canUseTool` nor `permissionPromptToolName`, denies any tool call that would have prompted, and this event reports those denials as well as the ones Claude Code decides on its own. Before v2.1.223, Claude Code didn’t emit this event in runs without a callback. + * **With an MCP prompt tool** , set with `permissionPromptToolName` or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) flag: Claude Code doesn’t emit this event at all, not even for the rule denials it decides on its own. + +In every configuration, this event skips any denial decided on the `PreToolUse` hook path, whether the hook denied the call itself or a deny rule overrode the hook’s allow or ask decision. The event is also best-effort: occasionally Claude Code records a denial without emitting this event, so `permission_denials` on the result message is the authoritative record. type SDKPermissionDeniedMessage = { type: "system"; @@ -1573,18 +1583,36 @@ body?: string; verifiedPeerPid?: number; } - | { kind: "task-notification" } + | { + kind: "task-notification"; + subkind?: "scheduled-trigger" | "peer-send-message"; + } | { kind: "coordinator" } - | { kind: "auto-continuation" }; + | { kind: "auto-continuation" } + | { kind: "unclassified" }; `kind`| Meaning ---|--- `human`| Direct input from the end user. If your application forwards what the user typed as a user message, set its `origin` to `{ kind: "human" }` explicitly: Claude Code treats a user message with no `origin` as unattributed, and checks that require a human-typed prompt, such as the [`ultracode` workflow keyword](</docs/en/workflows#ask-for-a-workflow-in-your-prompt>), don’t accept it. Before v2.1.210, Claude Code treated an absent `origin` on a user message as human input. `channel`| Message arriving on a [channel](</docs/en/channels>). `server` is the source MCP server name. `peer`| Message from another agent: an in-process [teammate](</docs/en/agent-teams>) or a [cross-session peer](</docs/en/cross-session-messaging>), another of your Claude Code sessions. See Peer origin fields for the per-field semantics and the trust model. -`task-notification`| Synthetic turn injected after a background task finished. See `SDKTaskNotificationMessage`. +`task-notification`| Synthetic turn injected for a delivery that arrives without a fresh user prompt, such as a finished background task; see `SDKTaskNotificationMessage` for that arm. The optional `subkind` marks what raised the notification. See Task-notification subkinds. `coordinator`| Message from a team coordinator in an [agent team](</docs/en/agent-teams>). `auto-continuation`| Synthetic turn injected when the session continues without fresh user input, such as a command result that triggers a follow-up prompt. +`unclassified`| Injected turn whose origin couldn’t be determined. Requires Claude Code v2.1.223 or later. When Claude Code receives an `SDKUserMessage` with `isSynthetic: true` and can’t classify it as any other `kind`, it sets this kind as the message arrives and frames the turn to the model as a non-user source rather than treating it as human input. Your application shouldn’t set this value. + +### + +​ + +Task-notification subkinds + +When Claude Code delivers a task notification into a session, it sets `subkind` on the notification’s `origin` only if Anthropic servers verified where that notification came from. `subkind` requires Claude Code v2.1.213 or later, and it takes one of two values: + + * `scheduled-trigger`: the notification is a [routine](</docs/en/routines>)’s stored prompt, delivered because one of the routine’s triggers fired: its schedule, its [API trigger](</docs/en/routines#add-an-api-trigger>), its [GitHub trigger](</docs/en/routines#add-a-github-trigger>), or **Run now**. Claude Code frames these to the model as the session’s assigned task, with a different notice from the notice that other task notifications carry. + * `peer-send-message`: the notification is a message that another of your sessions sent with the server-side `send_message` tool that [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions use to message each other, not the [cross-session `SendMessage` tool](</docs/en/cross-session-messaging>), and Anthropic servers verified that both sessions belong to the same private group of sessions. Requires Claude Code v2.1.224 or later. A `send_message` delivery the servers didn’t verify that way gets no subkind. + +Every other task notification has no `subkind`. That includes [scheduled tasks](</docs/en/scheduled-tasks>) that fire on your own machine, [PR activity](</docs/en/claude-code-on-the-web#how-claude-responds-to-pr-activity>) delivered into a session, and background events such as a finished task. Messages from the [cross-session `SendMessage` tool](</docs/en/cross-session-messaging>) aren’t task notifications at all: whether they come from a session on the same machine or through Anthropic servers from another machine, Claude Code gives them `kind: "peer"` and the peer origin fields. ### @@ -2232,7 +2260,8 @@ * A terminal escape sequence (e.g. OSC 9 / OSC 777 desktop-notification) * for Claude Code to emit on your behalf. Only notification/title OSCs * (0, 1, 2, 9, 99, 777) and BEL are permitted; a value containing - * anything else is ignored as a whole. + * anything else is ignored as a whole. Only the interactive CLI emits + * it; the SDK ignores the field. */ terminalSequence?: string; reason?: string; @@ -2416,7 +2445,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`. +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>). type AgentInput = { description: string; @@ -2941,14 +2970,24 @@ **Tool name:** `RemoteTrigger` type RemoteTriggerInput = { - action: "list" | "get" | "create" | "update" | "run"; + action: + | "list" + | "get" + | "create" + | "update" + | "run" + | "create_webhook_trigger" + | "list_runs" + | "get_run_log"; trigger_id?: string; + session_id?: string; + cursor?: string; body?: { [k: string]: unknown; }; }; -Manages [Routines](</docs/en/routines>), the scheduled and triggered Claude Code runs hosted in the cloud. This tool backs the `/schedule` command. `trigger_id` is required for the `get`, `update`, and `run` actions. `body` is required for `create` and `update`, and optional for `run`. This tool is available only when the session is authenticated with a claude.ai account on a plan with Routines enabled. +Manages [Routines](</docs/en/routines>), the scheduled and triggered Claude Code runs hosted in the cloud. This tool backs the `/schedule` command. `trigger_id` is required for the `get`, `update`, `run`, and `list_runs` actions. `body` is required for `create`, `update`, and `create_webhook_trigger`, and optional for `run`. `create_webhook_trigger` attaches an event source to an existing routine, such as a [GitHub event](</docs/en/routines#add-a-github-trigger>) that fires it. The `body` names the source, the events, and the routine to fire. Requires Claude Code v2.1.225 or later. `list_runs` lists a routine’s recent runs, and `get_run_log` reads one run’s log. `session_id` names the run to read, from a `list_runs` result, and `cursor` pages through either action’s results. Both actions require Claude Code v2.1.227 or later. This tool is available only when the session is authenticated with a claude.ai account on a plan with Routines enabled, and is absent when your organization’s policy disables [Claude Code on the web](</docs/en/claude-code-on-the-web>). On Claude Code v2.1.227 or later, the tool is also absent when an Owner has [turned off routines for the organization](</docs/en/routines#routines-are-disabled-by-your-organizations-policy>). Before v2.1.227, a session with only the routines toggle turned off still showed the tool, and the server denied its calls. ### @@ -3292,6 +3331,7 @@ backgroundedByUser?: boolean; timedOutAfterMs?: number; backgroundCwdHint?: string; + backgroundEndsWithFinalResponse?: true; dangerouslyDisableSandbox?: boolean; returnCodeInterpretation?: string; noOutputExpected?: boolean; @@ -3320,7 +3360,7 @@ `stderr`| Notices the tool itself adds, such as a shell working-directory reset, not the command’s stderr `backgroundTaskId`| Present for background commands -`timedOutAfterMs` is the timeout in milliseconds, set when the command reached its timeout and moved to the background rather than starting there explicitly. `backgroundCwdHint` is set when the backgrounded command contained a directory-change builtin such as `cd`, `pushd`, `popd`, or `chdir`, and notes that the session working directory didn’t change. Both fields require Claude Code v2.1.210 or later. +`timedOutAfterMs` is the timeout in milliseconds, set when the command reached its timeout and moved to the background rather than starting there explicitly. `backgroundCwdHint` is set when the backgrounded command contained a directory-change builtin such as `cd`, `pushd`, `popd`, or `chdir`, and notes that the session working directory didn’t change. Both fields require Claude Code v2.1.210 or later. When a subagent running in the foreground owns a backgrounded command, Claude Code terminates the command when that subagent gives its final response. Claude Code sets `backgroundEndsWithFinalResponse` to `true` on such commands, and omits the field when the command survives the turn, as commands started by the main conversation or by background subagents do. The field requires Claude Code v2.1.227 or later. ### @@ -4652,7 +4692,7 @@ session_id: string; }; -Claude Code prepends a notice to every task notification it sends to the model. The notice states that no human input has occurred, so the model doesn’t treat the notification as a user instruction or approval. To detect a task-notification turn, check `origin.kind === "task-notification"` on `SDKUserMessage` or `SDKResultMessage` rather than matching on the notice text. Before v2.1.205, Claude Code left the notice off notifications that arrived while the session was idle. +Claude Code prepends a notice to every task notification it sends to the model, except deliveries stamped with the `scheduled-trigger` subkind, which carry an assigned-task framing instead. The notice states that no human input has occurred, so the model doesn’t treat the notification as a user instruction or approval. To detect a task-notification turn, check `origin.kind === "task-notification"` on the `SDKUserMessage` or `SDKResultMessage` rather than matching on the notice text. Read `subkind` from the same field if you need to know what raised it. Before v2.1.205, Claude Code left the notice off notifications that arrived while the session was idle. ### @@ -4985,7 +5025,7 @@ `SDKConversationResetMessage` -Emitted when the session’s conversation is replaced without ending the session, such as after `/clear`, on plan-mode exit, or when a fresh conversation starts. Mount an empty transcript under `new_conversation_id` and discard any cached session title. +Emitted when the session’s conversation is replaced without ending the session. In a `query()` call, only `/clear` and its aliases produce this message. Mount an empty transcript under `new_conversation_id` and discard any cached session title. type SDKConversationResetMessage = { type: "conversation_reset";
modified Find bugs with ultrareview View current →
--- a/ultrareview.md +++ b/ultrareview.md @@ -43,6 +43,19 @@ /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. + +### + +​ + +Post findings to the pull request + +On Claude Code v2.1.227 or later, when you review a pull request on `github.com`, you can have Claude post the finished findings to the PR as a single plain comment from your own GitHub account. The comment isn’t a review or an approval, and it ends with a “Generated by Claude Code” note. When you review a branch or a GitHub Enterprise Server pull request, Claude Code shows the findings in your session only. Claude Code never posts unless you choose to on that run, and `--no-post` is the default. Posting is a choice you make for each run: + + * **Interactive** : in the launch dialog, select **Run and post the findings to the PR as me**. If you add `--post` to the command, as in `/code-review ultra 1234 --post`, Claude Code preselects that choice and still asks before launching. + * **Non-interactive** : run the `claude ultrareview` subcommand with `--post`. You consent to the post by running the subcommand with the flag, so Claude Code posts without asking. In a `claude -p '/code-review ultra'` run, Claude Code exits before the findings arrive, so it posts nothing; use the subcommand instead. + +Claude Code doesn’t post from your machine. It sends the findings to a session on [Claude Code on the web](</docs/en/claude-code-on-the-web>), which posts the comment through the GitHub account you’ve connected to Claude. Posting requires the same claude.ai sign-in as the review itself. Because posting runs through Claude Code on the web, it isn’t available on third-party providers or when you set [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars>). In an interactive session, Claude Code starts the post when the findings arrive, so keep the session open until the review finishes. Claude Code keeps the posting choice only in that session. If the session ends before the review finishes, Claude Code posts nothing, even if you resume the conversation later. When the post can’t start while your session is open, Claude tells you that nothing went to the PR and why, and the findings stay in your terminal so you can post them by hand. ### @@ -101,7 +114,7 @@ Track a running review -A review typically takes 5 to 10 minutes. The review runs as a background task, so you can keep working in your session, start other commands, or close the terminal entirely. Use `/tasks` to see running and completed reviews, open the detail view for a review, or stop a review that is in progress. If you stop a review, Claude Code archives the cloud session and doesn’t return partial findings. When the review finishes, the verified findings appear as a notification in your session. Each finding includes the file location and an explanation of the issue so you can ask Claude to fix it directly. +A review typically takes 5 to 10 minutes. The review runs as a background task, so you can keep working in your session, start other commands, or close the terminal entirely. If you chose to post the findings to the pull request, keep the session open until the review finishes; if the session ends first, Claude Code posts nothing. Use `/tasks` to see running and completed reviews, open the detail view for a review, or stop a review that is in progress. If you stop a review, Claude Code archives the cloud session and doesn’t return partial findings. When the review finishes, the verified findings appear as a notification in your session. Each finding includes the file location and an explanation of the issue so you can ask Claude to fix it directly. ## @@ -115,14 +128,16 @@ claude ultrareview 1234 claude ultrareview origin/main -Without arguments, the subcommand reviews the diff between your current branch and the default branch, with the same whole-repository fallback as `/code-review ultra` when no merge base exists. Pass a PR number to review a pull request, or a base branch to review against it; base-branch handling matches the interactive command. You consent to the whole-repository fallback and to the billing and terms prompt when you run the subcommand, so the run starts without waiting for input. On Claude Code v2.1.218 or later, you can also start the cloud review by running `/code-review ultra` in a non-interactive session, for example `claude -p '/code-review ultra'`. Claude Code launches the review and prints a tracking link without waiting for the findings, unlike `claude ultrareview`, which blocks until they arrive. When the review would bill usage credits, Claude Code stops before launching and points you to `claude ultrareview`, because the billing confirmation needs an interactive session. Before v2.1.218, `/code-review ultra` in a non-interactive session ran a local review. Progress messages and the live session URL go to stderr so stdout stays parseable. Use these flags to control the output and timeout: +Without arguments, the subcommand reviews the diff between your current branch and the default branch, with the same whole-repository fallback as `/code-review ultra` when no merge base exists. Pass a PR number to review a pull request, or a base branch to review against it; base-branch handling matches the interactive command. You consent to the whole-repository fallback and to the billing and terms prompt when you run the subcommand, so the run starts without waiting for input. On Claude Code v2.1.218 or later, you can also start the cloud review by running `/code-review ultra` in a non-interactive session, for example `claude -p '/code-review ultra'`. Claude Code launches the review and prints a tracking link without waiting for the findings, unlike `claude ultrareview`, which blocks until they arrive. When the review would bill usage credits, Claude Code stops before launching and points you to `claude ultrareview`, because the billing confirmation needs an interactive session. Before v2.1.218, `/code-review ultra` in a non-interactive session ran a local review. Progress messages and the live session URL go to stderr so stdout stays parseable. Use these flags to control the output, the timeout, and whether to post the findings: Flag| Description ---|--- `--json`| Print the raw `bugs.json` payload instead of the formatted findings `--timeout <minutes>`| Maximum minutes to wait for the review to finish. Defaults to 30 +`--post`| Post the finished findings to the pull request as one plain comment from your GitHub account. Works on `github.com` pull request targets; on other targets, Claude Code ignores the flag and says so. Requires Claude Code v2.1.227 or later +`--no-post`| Don’t post the findings. This is the default, and if you pass both flags, Claude Code doesn’t post. Requires Claude Code v2.1.227 or later -Running `claude ultrareview` requires the same authentication and usage credit configuration as `/code-review ultra`. The subcommand exits with code 0 when the review completes with or without findings, code 1 when the review fails to launch, the cloud session errors, or the timeout elapses, and code 130 when interrupted with Ctrl-C. The remote review keeps running if you interrupt the subcommand; follow the session URL printed to stderr to watch it in the browser. For automatic reviews on GitHub pull requests, [Code Review](</docs/en/code-review>) integrates with your repository directly and posts findings as inline PR comments without a CLI step. +Running `claude ultrareview` requires the same authentication and usage credit configuration as `/code-review ultra`. The subcommand exits with code 0 when the review completes with or without findings, code 1 when the review fails to launch, the cloud session errors, or the timeout elapses, and code 130 when interrupted with Ctrl-C. The remote review keeps running if you interrupt the subcommand; follow the session URL printed to stderr to watch it in the browser. With `--post`, the subcommand starts the post right after it prints the findings. If the run fails, times out, or you interrupt it, the subcommand posts nothing. If the review completes but the post can’t start, Claude Code prints the reason to stderr, and the findings stay on stdout so you can post them by hand. For automatic reviews on GitHub pull requests, [Code Review](</docs/en/code-review>) integrates with your repository directly and posts findings as inline PR comments without a CLI step. ##
modified Voice dictation View current →
--- a/voice-dictation.md +++ b/voice-dictation.md @@ -70,7 +70,7 @@ Tap to record and send -Tap mode toggles recording with a single keypress: tap once to start, speak, then tap again to send the prompt. There is no warmup, and you don’t need to keep the key held. Enable tap mode with `/voice tap`. With the prompt input empty, tap `Space` to start recording. The footer shows a live waveform while recording. Tap `Space` again to stop. Claude Code inserts the transcript and submits the prompt automatically when the transcript is at least three words long. Shorter transcripts are inserted but not submitted, so an accidental tap does not send a stray word. The three-word threshold counts words for languages written without spaces. As of v2.1.195, Japanese, Chinese, and Thai transcripts count individual words, so they auto-submit in tap mode and in hold mode with `autoSubmit`. Earlier versions counted a transcript with no spaces as one word and never submitted it automatically. The first tap only starts recording when the prompt input is empty, so you can still type spaces normally while composing a message. The second tap stops recording regardless of input contents. Recording also stops automatically after 15 seconds of silence or two minutes total. +Tap mode toggles recording with a single keypress: tap once to start, speak, then tap again to send the prompt. There is no warmup, and you don’t need to keep the key held. Enable tap mode with `/voice tap`. With the prompt input empty, tap `Space` to start recording. The footer shows a live waveform while recording. Tap `Space` again to stop. Claude Code inserts the transcript and submits the prompt automatically when the transcript is at least three words long. Shorter transcripts are inserted but not submitted, so an accidental tap does not send a stray word. The three-word threshold counts words for languages written without spaces. Japanese, Chinese, and Thai transcripts count individual words, so they auto-submit in tap mode and in hold mode with `autoSubmit`. The first tap only starts recording when the prompt input is empty, so you can still type spaces normally while composing a message. The second tap stops recording regardless of input contents. Recording also stops automatically after 15 seconds of silence or two minutes total. ##
modified Use Claude Code in VS Code View current →
--- a/vs-code.md +++ b/vs-code.md @@ -82,13 +82,14 @@ The prompt box supports several features: - * **Permission modes** : click the mode indicator at the bottom of the prompt box to switch modes, or set the default in VS Code settings under `claudeCode.initialPermissionMode`. See [permission modes](</docs/en/permission-modes#switch-permission-modes>) for every mode the indicator offers. + * **Permission modes** : click the mode indicator at the bottom of the prompt box to switch modes, or set the default in your VS Code user settings under `claudeCode.initialPermissionMode`. See [permission modes](</docs/en/permission-modes#switch-permission-modes>) for every mode the indicator offers. * **Manual** : Claude asks permission before file edits and most shell commands. * **Plan** : Claude describes what it will do and waits for approval before making changes. VS Code automatically opens the plan as a full Markdown document where you can add inline comments to give feedback before Claude begins. * **Edit automatically** : Claude makes edits without asking. * **Command menu** : click `/` or type `/` to open the command menu. Options include attaching files, switching models, toggling extended thinking, viewing plan usage (`/usage`), and starting a [Remote Control](</docs/en/remote-control>) session (`/remote-control`). The Customize section provides access to MCP servers, hooks, memory, permissions, and plugins. Items with a terminal icon open in the integrated terminal. * The Settings section includes **Enable Remote Control for all sessions** , which sets [`remoteControlAtStartup`](</docs/en/settings#available-settings>) to control whether [new interactive sessions connect to Remote Control automatically](</docs/en/remote-control#enable-remote-control-for-all-sessions>). Requires Claude Code v2.1.203 or later. - * The Settings section also includes **Focus view** , which hides tool calls, tool results, and thinking behind one expandable row per turn, leaving your prompts and Claude’s responses. While Claude works, the row shows the tool currently running. When you turn Focus view on or off, the change applies to every open session immediately, and the choice persists across sessions. You can also toggle it with `Ctrl+Option+F` (Mac) / `Ctrl+Alt+F` (Windows/Linux), or from the Command Palette with **Claude Code: Toggle Focus view**. Requires Claude Code v2.1.221 or later. + * The Settings section also includes **Focus view** , which hides tool calls, tool results, and thinking behind expandable rows, leaving your prompts and Claude’s responses. Claude’s latest to-do list stays visible, and so does the text a pending question from Claude is asking about. Toggle it there, with `Ctrl+Option+F` (Mac) / `Ctrl+Alt+F` (Windows/Linux), or from the Command Palette with **Claude Code: Toggle Focus view**. The change applies to every open session and persists across sessions. Requires Claude Code v2.1.221 or later. + * **Side questions** : type `/btw` followed by a question, or pick it from the command menu, to ask about your session [without adding to the conversation](</docs/en/interactive-mode#side-questions-with-%2Fbtw>). The answer opens in a panel beside the chat, where you can ask follow-up questions. The thread survives window reloads. Claude Code keeps the newest 20 exchanges and expires stored threads on the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) schedule, as long as Claude Code can [safely determine the retention period](</docs/en/claude-directory#cleaned-up-automatically>). To clear a thread, click the trash icon in the panel. Requires Claude Code v2.1.227 or later. * **Context indicator** : the prompt box shows how much of Claude’s context window you’re using. Claude automatically compacts when needed, or you can run `/compact` manually. * **Extended thinking** : lets Claude spend more time reasoning through complex problems. Toggle it on via the command menu (`/`). Claude’s reasoning appears in the conversation as collapsed blocks: click a block to read it, or press `Ctrl+O` to expand or collapse every thinking block in the session. See [Extended thinking](</docs/en/model-config#extended-thinking>) for details. * **Multi-line input** : press `Shift+Enter` to add a new line without sending. This also works in the “Other” free-text input of question dialogs. @@ -329,17 +330,19 @@ Extension settings +VS Code reads `initialPermissionMode` from your user settings and ignores workspace values. Before v2.1.225, VS Code defaulted the setting to `default` and applied workspace values. + Setting| Default| Description ---|---|--- `useTerminal`| `false`| Launch Claude in terminal mode instead of graphical panel -`initialPermissionMode`| `default`| Controls approval prompts for new conversations: `default`, `plan`, `acceptEdits`, or `bypassPermissions`. `manual` is an alias for `default` and selects the mode labeled **Manual** in the mode indicator. Requires Claude Code v2.1.200 or later. See [permission modes](</docs/en/permission-modes>). +`initialPermissionMode`| -| Controls approval prompts for new conversations: `default`, `plan`, `acceptEdits`, or `bypassPermissions`. `manual` is an alias for `default` and selects the mode labeled **Manual** in the mode indicator. When you leave it unset, Claude Code resolves the session’s starting mode itself. See [how to switch permission modes and set the session default](</docs/en/permission-modes#switch-permission-modes>). `preferredLocation`| `panel`| Where Claude opens: `sidebar` (right) or `panel` (new tab) `autosave`| `true`| Auto-save files before Claude reads or writes them `useCtrlEnterToSend`| `false`| Use Ctrl/Cmd+Enter instead of Enter to send prompts `enableNewConversationShortcut`| `false`| Enable Cmd/Ctrl+N to start a new conversation `enableReopenClosedSessionShortcut`| `true`| Use Cmd/Ctrl+Shift+T to reopen the most recently closed Claude session tab. When the last closed tab wasn’t a Claude session, the shortcut runs VS Code’s normal reopen-closed-editor command instead. `hideOnboarding`| `false`| Hide the onboarding checklist (graduation cap icon) -`focusView`| `false`| Hide tool calls, tool results, and thinking behind one expandable row per turn, leaving your prompts and Claude’s responses. You can also toggle Focus view from the command menu. Requires Claude Code v2.1.221 or later +`focusView`| `false`| Hide tool calls, tool results, and thinking behind expandable rows, leaving your prompts and Claude’s responses. Claude’s latest to-do list stays visible. You can also toggle Focus view from the command menu. Requires Claude Code v2.1.221 or later `respectGitIgnore`| `true`| Exclude .gitignore patterns from file searches `usePythonEnvironment`| `true`| Activate the workspace’s Python environment when running Claude. Requires the Python extension. `environmentVariables`| `[]`| Set environment variables for the Claude process. Use Claude Code settings instead for shared config.
modified Run parallel sessions with worktrees View current →
--- a/worktrees.md +++ b/worktrees.md @@ -69,13 +69,14 @@ How Claude Code enforces isolation -While a session is isolated in a worktree, whether you started it with `--worktree`, Claude entered one with `EnterWorktree`, or you resumed a worktree session, Claude Code blocks the tool calls listed below when they would reach the main checkout. The same enforcement covers every subagent Claude spawns from the isolated session, and it applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks; their version history is under [Write subagent files](</docs/en/sub-agents#write-subagent-files>). Claude Code applies three checks: +While a session is isolated in a worktree, Claude Code blocks the tool calls the checks below define. The same rules apply whether you started the session with `--worktree`, Claude entered a worktree with `EnterWorktree`, or you resumed a worktree session. The same enforcement covers every subagent Claude spawns from the isolated session. It applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks. Their version history is under [Write subagent files](</docs/en/sub-agents#write-subagent-files>). Claude Code applies four checks: * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. * **Command working directory** : Claude Code blocks a Bash, PowerShell, or Monitor command whose working directory resolves to the main checkout, or whose working directory it can’t verify stays outside it. - * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout, whether through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. Claude Code also blocks a command it can’t verify stays inside the worktree. For PowerShell commands, Claude Code applies only the working-directory check. - -The checks apply to the repository you launched Claude Code from, including the main checkout a linked worktree is linked from. Claude sees each refusal as a tool error that names the worktree and says how to proceed. + * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout. The redirect can come through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. + * **Command shape** : Claude Code blocks a Bash or Monitor command it can’t verify stays inside the worktree. The block applies even when the command runs no git at all. Claude Code refuses shell constructs it can’t statically trace, such as brace expansion and heredocs with unquoted delimiters. It tells Claude to break the command into plain, separate commands. You can’t turn this check off. + +The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. ## @@ -102,7 +103,7 @@ Clean up subagent and background-session worktrees -A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting. The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`. 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. +A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`. 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. ##