modified Manage multiple agents with agent view View current →
--- a/agent-view.md +++ b/agent-view.md @@ -311,7 +311,7 @@ ​ -From agent view +Dispatch an agent from agent view Type a prompt in the input at the bottom of agent view and press `Enter` to start a new background session. The session is named automatically from the prompt; rename it later with `Ctrl+R`. The automatic name is a short label written by a [Haiku-class model](</docs/en/model-config>). A name the session gets later also appears on its row, including the [generated title](</docs/en/sessions#name-your-sessions>) the session gets when you [accept a plan](</docs/en/permission-modes#review-and-approve-a-plan>) in that session. Paste an image into the prompt to include a screenshot or diagram with the task. Pasted text longer than 800 characters or more than three lines collapses to a `[Pasted text #N]` placeholder so the input stays on one line; the full text is sent when you dispatch. To review or edit the collapsed text before dispatching, paste the same text again and the placeholder expands back into the input. Prefix or mention parts of the prompt to control how the session starts: @@ -356,7 +356,7 @@ ​ -From inside a session +Send or copy a session to the background Two commands move work from the session you’re in to the background: `/background` sends the current conversation there and frees your terminal, and `/fork` sends a copy while you keep working where you are. @@ -405,7 +405,7 @@ ​ -From your shell +Dispatch an agent from your shell Pass `--bg` or its long form `--background` to start a session that goes straight to the background: @@ -644,7 +644,7 @@ `claude daemon logs`| Follow the supervisor’s log file, `~/.claude/daemon.log`, printing new lines as they arrive until you press `Ctrl+C` `claude daemon stop --any`| Stop the supervisor process and the background sessions it hosts. Pass `--keep-workers` to leave background sessions running so the next supervisor reconnects to them. The next `claude agents` or `claude --bg` starts a fresh supervisor -`claude attach` and `claude logs` can take part of a running session’s name in place of the ID, as in `claude logs "auth refactor"`. Passing a name requires Claude Code v2.1.290 or later. +`claude attach` and `claude logs` can take part of a session’s name in place of the ID, as in `claude logs "auth refactor"`. Passing a name requires Claude Code v2.1.290 or later. ### @@ -919,7 +919,7 @@ Version| Change ---|--- -v2.1.290| `claude attach` and `claude logs` can take part of a running session’s name in place of the ID. +v2.1.290| `claude attach` and `claude logs` can take part of a session’s name in place of the ID. v2.1.290| `/model`, `/effort`, `/rename`, and `/usage` sent as a peek reply to a working session run right away. v2.1.290| A peek reply that can’t be delivered is no longer saved for the next restart when it starts with `/`, or when it answers a question with predefined choices while the session’s process is running. v2.1.288| `Ctrl+F` finds sessions by name, and `Alt+↑` / `Alt+↓` jump between group headers. Both, and `Ctrl+R`, can be [rebound](</docs/en/keybindings#agents-actions>).
modified Use the mods API View current →
Show diff (109 lines)
--- a/api.md +++ b/api.md @@ -67,7 +67,25 @@ Call a model -A mod can ask a model a question of its own, outside the conversation, for a small job such as sorting or summarizing a piece of text. `$.model.complete` sends one prompt to a model with your session’s credentials and resolves to the reply. It has no conversation history. This hook answers a `/triage` command, registered as a command, by asking a small model to label the text typed after it: +A mod can send its own requests to a model for a small job such as classifying or summarizing text. `$.model.complete` sends your prompt on its own, and `$.model.fork({ prompt })` sends the current conversation with your prompt at the end. This table compares what each request contains: + +In the request| `$.model.complete`| `$.model.fork` +---|---|--- +Model| The `model` you pass| The session’s model +System prompt| A short [attribution block](</docs/en/llm-gateway-protocol#system-prompt-attribution-block>), then your `system` if you pass one| The session’s system prompt +Messages| One user message, your `prompt`| The conversation so far, then your `prompt` as a user message +CLAUDE.md and other project context| Not included| Included, as in the conversation’s last request +Tools| None| Claude’s tools, which the model can’t call + +A fork repeats the conversation’s last request, so the Claude API serves most of it from the [prompt cache](</docs/en/prompt-caching>) while the conversation is still cached. Both calls use the session’s credentials, so they bill to the user’s plan, API key, or cloud provider. [The types for your build](</docs/en/plugins/mods/create#get-the-types-for-your-build>) document every `$.model` method. + +### + +​ + +Send one prompt + +Pass `model` and `prompt` to `$.model.complete`. `prompt` becomes the user message. To give the model instructions, such as a role or an output format, also pass `system`, which becomes the system prompt. This hook answers a `/triage` command, registered as a command, by asking a small model to label the text typed after it: on('command.run', { command: 'triage' }, async ($, e) => { const r = await $.model.complete({ @@ -84,7 +102,78 @@ return { text: 'Label: ' + label } }) -When you run `/triage the export button does nothing`, the mod sends that text to the model and prints its answer, such as `Label: bug`. Claude’s conversation isn’t part of the request. When the model doesn’t answer, the label is `unknown`. A Claude API failure doesn’t reject the call, so check `r.isAnswered`, and read `r.reason` when it’s `false`. The call rejects for a request Claude Code won’t send, such as a model your organization blocks. [The types for your build](</docs/en/plugins/mods/create#get-the-types-for-your-build>) list the other options, such as `effort`, and the [limits](</docs/en/plugins/mods/reference#limits>) give the `maxTokens` default. `$.model.fork({ prompt })` asks one question over the current conversation instead, with the same model and system prompt, so the Claude API serves most of it from the prompt cache. These calls use the user’s plan or API key. +When you run `/triage the export button does nothing`, the mod sends that text to the model and prints its answer, such as `Label: bug`. When the model doesn’t answer, the label is `unknown`. A Claude API failure doesn’t reject the call, so check `r.isAnswered`, and read `r.reason` when it’s `false`. The call rejects for a request Claude Code won’t send, such as a model your organization blocks. [The types for your build](</docs/en/plugins/mods/create#get-the-types-for-your-build>) list the other options, such as `effort`, and the [limits](</docs/en/plugins/mods/reference#limits>) give the `maxTokens` default. + +### + +​ + +Use prompt caching + +`$.model.complete` supports the Claude API’s [prompt caching](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching>). The API caches the start of a request, called the prefix, up to a [cache breakpoint](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#explicit-cache-breakpoints>) that you set. When every call starts with the same long static content, such as instructions or reference material, set a breakpoint at the end of that content. Later calls then read it from the cache instead of paying the full input price for it. To set a breakpoint, pass `prompt` as an array of `{ text }` blocks instead of a string, and add `cache: true` to the last block of the static content. Claude Code sends that block with the API’s `cache_control` field. `system` takes the same array form. To decide between them, see Choose between `prompt` and `system`. + +Arrays of blocks require Claude Code v2.1.292 or later. Earlier versions reject an array in `prompt` with an error that ends with `takes { model, prompt } (host check)`, and they leave an array in `system` out of the request. + +This version of the `/triage` hook sends a long set of labeling rules before the text to label, with a breakpoint after the rules. `RULES` is a string of your own: + + on('command.run', { command: 'triage' }, async ($, e) => { + const r = await $.model.complete({ + model: 'haiku', + prompt: [ + // Identical on every call, so it forms the cached prefix + { text: RULES, cache: true }, + // Changes on every call, so it goes after the breakpoint + { text: e.args }, + ], + }) + return { text: 'Label: ' + (r.isAnswered ? r.text.trim() : 'unknown') } + }) + +The TTL and the number of breakpoints have these limits: + + * **TTL** : a cache entry lasts five minutes after its last use. The TTL comes from the user’s Claude Code settings, not from the call. For one hour, set [`subagentPromptCacheTtl`](</docs/en/prompt-caching#choose-the-ttl-yourself>) to `1h`. + * **Breakpoints per request** : the API accepts [up to four](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#when-to-use-multiple-breakpoints>), and one more comes back as an `api-error` in `r.reason` + +#### + +​ + +Choose between `prompt` and `system` + +Put the static content that your calls share at the start of `prompt` unless you know that your requests go directly to the Claude API: + + * **Directly to the Claude API, with an API key or a Claude subscription** : either field works + * **Through[Amazon Bedrock](</docs/en/amazon-bedrock>), [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), or an [LLM gateway](</docs/en/llm-gateway>)**: use `prompt`. Claude Code begins the system prompt with an [attribution block](</docs/en/llm-gateway-protocol#system-prompt-attribution-block>) whose fingerprint comes from the start of the user message. The `api.anthropic.com` endpoint strips that block before caching. Other endpoints receive it as part of the prompt, so a breakpoint in `system` can miss when `prompt` starts differently. + * **In a mod that other people run** : use `prompt`, because you don’t choose their provider + +`system` comes before `prompt` in the prefix, so a breakpoint in `prompt` covers `system` too, and a call with a different `system` misses the cache. + +#### + +​ + +Check for cache hits + +The result of `$.model.complete` has a `usage` object with the API’s [cache fields](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#tracking-cache-performance>). `usage.cache_creation_input_tokens` counts the tokens the call wrote to the cache, and `usage.cache_read_input_tokens` counts the tokens it read from the cache. Expect a write on the first call and reads on later calls within the TTL. If every call writes and none reads, the prefix differs between calls or the calls are further apart than the TTL. For a prefix that differs, see Choose between `prompt` and `system`. If both fields stay at zero on calls the model answered, nothing was cached. Check for each of these causes: + + * **The prefix is too short** : the API doesn’t cache a prefix under the model’s [minimum length](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#cache-limitations>), and it returns no error + * **Prompt caching is disabled** : when a [`DISABLE_PROMPT_CACHING` variable](</docs/en/prompt-caching#disable-prompt-caching>) applies to the model, Claude Code removes the breakpoints and sends the text uncached + * **Your gateway strips`cache_control`**: a gateway can [remove the field and still return success](</docs/en/prompt-caching#where-the-cache-lives>) + * **Another mod rewrites the start of the text** : Claude Code then sends it without breakpoints + +### + +​ + +What a `model.complete` hook receives + +If you hook the [`model.complete`](</docs/en/plugins/mods/reference#mods-api-calls>) event to inspect or change other mods’ requests, read the text from these fields: + + * **`e.prompt`** : always a string. When the caller passed an array, it’s the blocks’ text concatenated in order. + * **`e.system`** : a string built the same way, or absent when the caller passed no `system` + * **`e.promptBlocks` and `e.systemBlocks`**: the caller’s arrays, each present when the caller passed an array for that field + +Claude Code sends the strings your hook passes to `next` and uses the arrays you pass with them to place cache breakpoints. It keeps the leading blocks that still match the start of the string, with their breakpoints, and sends the rest of the string with no breakpoint. For example, `next({ ...e, prompt: e.prompt + NOTE })` keeps the caller’s breakpoints, and a hook that changes the start of `prompt` removes them. ##
modified Claude Code changelog View current →
Show diff (104 lines)
--- a/changelog.md +++ b/changelog.md @@ -1,4 +1,101 @@ This page is generated from the [CHANGELOG.md on GitHub](<https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md>). Longer releases are grouped by type of change, with long lists of improvements and bug fixes collapsed. Run `claude --version` to check your installed version. + +​ + +2.1.296 + +October 9, 2026 + +**Added** + + * Added a `code` key to the Claude apps gateway’s `managed.policies[]`: the same settings as `cli`, also applied in Claude Desktop’s Code tab; beside `desktop`, it turns on Claude Desktop’s gateway mode + * Added `autoCompactWindow` to subagent frontmatter and `--agents` definitions, so a subagent can auto-compact earlier than the main conversation’s window + * Added `CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL` to run every workflow agent on one model while other subagents keep theirs + * Added `CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS` environment variable to set a longer maximum delay for the backoff when retrying an overloaded (529) request + * Added a note in `/plugin` on a plugin whose hooks are left out because another enabled plugin has the same name + * Added an `allow_large` option to the Read tool so Claude can read a text file past the usual size limits in one call when it needs the whole file and the context has room + * [Cloud sessions] Added a status filter to the Sessions and Runners lists on a self-hosted environment’s Activity tab in admin settings; you can pick several statuses at once + * [Claude Tag] Added creating, editing and deleting workspace and channel memory files on the Activity page’s Memory tab for members with the Claude Tag Admin permission + +**Changed** + + * Updated `/cost`, the status line, `--max-budget-usd` and the SDK’s cost figures to price Sonnet 5.5 cache reads at 0.10permilliontokens(was0.10 per million tokens (was 0.10permilliontokens(was0.20) + * Updated the bundled dataviz skill: lighter violet for the seventh series in light mode, softer primary text in dark mode, and compact y-axis labels like 1K + * Changed the default limit on MCP tool descriptions sent up front and on MCP server instructions from 2,048 to 4,096 characters + * Changed `←`: a turn or `!` command started while the session moves to the background is now stopped instead of finishing out of sight + * [VSCode] Changed Claude in Chrome to ask before browser actions in every session, including one connected with `@browser`, as the terminal does; allowing a site for the session stops repeat asks + * [Claude Tag] Changed Claude in Slack to show the footer with the session link, model and cost only on its newest reply in a thread; the reply before it drops the footer + +Show 9 improvements + + * Improved fullscreen mode: the link under the mouse pointer is now underlined to show it can be opened + * Improved transcript toggle (ctrl+o) responsiveness in code-heavy conversations by caching syntax-highlighted code blocks + * Improved Claude Desktop’s Code tab behind a Claude apps gateway: when a session can’t start, including on a machine not set up for the gateway’s `code` settings, the reason shows as a reply + * Improved the errors for a refused cloud session: they now say why your organization’s policy couldn’t be loaded, and name an API key or auth token that overrides your claude.ai login + * Improved `--debug` output to name unrecognized frontmatter fields in custom agent files, with a hint for likely typos + * Improved auto mode: a tool call that wasn’t run because auto mode’s check had no usable answer now shows as a dim “Not run” row instead of a red error + * Improved `--debug` output for hooks: command hooks on tool calls, prompts, SessionStart and Stop now log their command, plugin, outcome and duration when they finish, so a slow hook is identifiable + * Improved `CLAUDE_CODE_TRANSCRIPT_LOCAL_GC`: a large transcript file is no longer rewritten when that would free under 10% of it + * [Code Review] Improved Code Review admin settings to say why a setting couldn’t be saved, such as a policy restriction, instead of a generic failure message + +Show 56 bug fixes + + * Fixed managed-settings `PreToolUse` hooks that deny a tool call with `"continue": false`, and managed `prompt` hooks that block one, refusing the call but not ending the turn + * Fixed PostToolUse hooks in managed settings not applying `updatedMCPToolOutput` in some sessions + * Fixed headless sessions starting a folder’s `.mcp.json` or plugin MCP server that was switched off for that folder, after changing directory or reloading plugins + * Fixed a Claude apps gateway that serves `allowedProviders` with `"gateway"` locking out laptops that name that gateway in user settings + * Fixed a saved Claude apps gateway sign-in being ignored on machines whose managed settings set `forceLoginMethod` to `gateway` with no `forceLoginGatewayUrl` (regression in 2.1.295) + * Fixed `--teleport` opening an empty conversation when the session’s history could not be read + * Fixed token counts for Haiku 5.5 and other models that take only adaptive thinking, which failed behind some gateways and were counted with budget thinking elsewhere + * Fixed resumed subagents being told that the user rejected a tool call that a session shutdown had interrupted + * Fixed hook output being altered when it contained text resembling a plugin hint tag + * Fixed secret redaction in shared transcripts and debug logs missing some values that follow a key with no value, including in JSON written inside a shell string + * Fixed a stray `52;c;…` escape sequence printed on screen after copying in older VTE-based terminals such as MATE Terminal + * Fixed toasts and notifications waiting unseen for as long as the `/diff` panel or dialog was open + * Fixed Esc or an interrupt during a `UserPromptSubmit` hook or a mod’s `prompt.submit` hook ending headless sessions, clearing the typed prompt, or letting the unchecked prompt through + * Fixed SessionStart hooks of a plugin loaded after a headless session starts being skipped when a different plugin with the same name, or another spelling of it, had already run + * Fixed `claude self-hosted-runner` printing misleading errors when registration is refused: it now names the org admin setting, or says a restarted on-demand runner needs a fresh work order + * Fixed a self-hosted runner session’s git fetch, pull and push failing while another session of the same repository starts on a runner with `--capacity` above 1 + * Fixed workflow scripts silently truncating results, agent options and other values nested deeper than about 20,000 levels, and deeply nested results writing huge task output files + * Fixed a plugin’s served `$` methods running in the main session’s working directory instead of the calling agent’s, and ignoring the turn their calling hook holds + * Fixed `$.agent.register` succeeding from a mod’s hook that was still running after the mod was reloaded or removed; the call is now refused + * Fixed `$.http.fetch` in mods refusing a `HEAD` request when the response declares a `Content-Length` over the 4 MiB body limit + * Fixed `claude plugin marketplace add`, `marketplace update` and `plugin install` failing with an internal error for a marketplace named like `constructor`; `add` now refuses such names clearly + * Fixed a plugin secret named `constructor` or `prototype` being deleted by the next save of that plugin’s options + * Fixed cloud sessions skipping auto mode’s checks on Claude in Chrome actions that a saved permission allows when their feature flags had not loaded + * Fixed `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` re-running a finished turn after a restart when an MCP tool result had ended that turn + * Fixed Bash permission checks auto-approving some commands that assign the `BASH_ARGV0` shell variable and then use it; these now prompt for approval + * Fixed Edit and NotebookEdit replacing every non-ASCII character in files that are not valid UTF-8 (Windows-1252, Shift-JIS, GBK); such edits are now refused + * Fixed a prompt sent just after `←` being run twice, once unseen in the foreground, when the background service was slow to answer + * Fixed a prompt sent while SessionStart hooks were still running vanishing when `←` moved the session to the background; it is still not sent, but `↑` now brings it back + * Fixed a late-loading plugin’s SessionStart hook output reaching the new conversation after `/clear` in headless sessions + * Fixed PowerShell commands not seeing variables that hooks write to CLAUDE_ENV_FILE (when the file holds only plain assignments) + * Fixed Claude calling cloud sessions non-interactive and suggesting `/mcp` or `claude mcp` when an MCP server needs authentication + * Fixed `/code-review` ending on a raw JSON array in cloud sessions, the Agent SDK and IDE integrations; the findings now print as a numbered list + * Fixed auto mode occasionally refusing one update to your own artifact, saying its sharing had changed when it had not + * Fixed skills synced from claude.ai never finishing their install, and being downloaded again at every sync, when several sessions share a config directory + * Fixed a plugin synced from claude.ai being disabled when the marketplace dependency it declares was also synced from claude.ai + * Fixed a startup hang on macOS when plugin paths copied from a Linux machine pointed under /home + * Fixed the Workflow tool refusing script files with CRLF line endings, such as files checked out on Windows + * Fixed OpenTelemetry `tool_result` events missing `git_commit_id` after `git commit -q` or `git -C <dir> commit` + * Fixed `CLAUDE_CODE_TRANSCRIPT_LOCAL_GC` dropping a message from the saved transcript when its text held a Unicode line or paragraph separator (U+2028, U+2029) + * Fixed `claude purge` leaving a prompt in the history file when its text held a Unicode line or paragraph separator (U+2028, U+2029) + * Windows: Fixed PowerShell commands longer than about 1 KB always asking for permission, so allow rules and read-only detection now apply up to 32 KB + * Windows: Fixed stdio MCP servers being force-killed at shutdown; stdin now closes first and the process tree is killed only if the server is still running after 300 ms + * Windows: Fixed `claude plugin install` failing for GitHub `owner/repo` plugin sources on machines with no GitHub SSH key; the clone is now retried over HTTPS + * Windows: Fixed `rm -rf /c/Users/<name>` in Git Bash not asking in bypass permissions mode + * [VSCode] Fixed `claudeCode.spinnerVerbs` missing from the extension’s settings, so settings.json now completes and validates it; a malformed value no longer breaks the chat panel + * [VSCode] Fixed chat links written as a full Windows path, such as C:\repo\file.ts or file:///C:/repo/file.ts, not opening the file on Windows + * [VSCode] Fixed the working indicator still animating when reduced motion is turned on in your OS, in VS Code, or with the `prefersReducedMotion` setting + * [VSCode] Fixed the prompt cache clock reading warm after the panel caught up on messages late, such as after the display was off or a remote window reconnected + * [Cloud sessions] Fixed every cloud session waiting for a self-hosted runner showing the same queue position; each now shows how many sessions are ahead of it + * [Cloud sessions] Fixed a message you send while Claude is still replying in a cloud session jumping above that reply when it finishes; it now stays below it, including after a reload + * [Claude Tag] Fixed links to URLs that contain parentheses breaking in some of Claude’s Slack replies and task checklists, which showed stray bracket text and opened the wrong page + * [Claude Tag] Fixed Claude’s Slack replies drawing color swatches beside codes that only look like hex colors, such as six-digit pull request numbers + * [Claude Tag] Fixed the plugin confirmation card Claude posts in a Slack channel showing a plugin’s ID instead of its name + * [Claude Tag] Fixed Claude in Slack posting a card to remove a plugin the channel’s own settings don’t include; it now explains where the plugin comes from instead + * [Claude Tag] Fixed Claude in Slack sometimes losing its reply when a session in a self-hosted environment moved to a new runner partway through a task + * [Code Review] Fixed the Code Review check sometimes staying “in progress” on a pull request after the review finished; it now shows the review’s result ​
modified Use Claude Code with Chrome View current →
--- a/chrome.md +++ b/chrome.md @@ -109,10 +109,7 @@ Permission prompts in VS Code sessions -In a VS Code session, whether Claude Code asks you before a browser action depends on how the session connected to your browser: - - * **You typed`@browser`**: the extension approves each browser action that Claude Code would otherwise ask you about. - * **TheEnabled by default setting connected it at start**: Claude Code asks you before browser actions on a site you haven’t allowed, in Manual, Edit automatically, Auto, and Bypass permissions modes, until you type `@browser` in that session. +In a VS Code session, when Claude Code asks before a browser action, the prompt appears as a card in the chat panel. When the action targets a site you haven’t allowed, the card also offers to allow that site. In a session that connected to your browser at start because Enabled by default is on, Claude Code asks you before browser actions on a site you haven’t allowed, in Manual, Edit automatically, Auto, and Bypass permissions modes. In Auto and Bypass permissions modes, this applies until you type `@browser` in that session. ### @@ -120,7 +117,7 @@ Browser tools in plan mode -In [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>), a permission prompt appears before Claude records a GIF, opens a new tab, or runs a shortcut, except in a VS Code session where you typed `@browser`. In an interactive CLI session, if [bypass permissions mode is available](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) and [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>) is off, these calls run without a prompt. A `tabs_context_mcp` call also prompts when it sets `createIfEmpty`, and so does a `browser_batch` call that includes any of these actions. +In [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>), a permission prompt appears before Claude records a GIF, opens a new tab, or runs a shortcut. In an interactive CLI session, if [bypass permissions mode is available](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) and [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>) is off, these calls run without a prompt. A `tabs_context_mcp` call also prompts when it sets `createIfEmpty`, and so does a `browser_batch` call that includes any of these actions. ## @@ -182,11 +179,12 @@ Open the bug tracker at bugs.example.com, create a new issue, and attach logs/session.log to it -Three restrictions apply to uploads: +If Claude refuses to attach a file or an upload fails, check for these causes: * **Permissions** : Claude can upload a file only when the session is allowed to read it, so [permission rules](</docs/en/settings-reference#permission-settings>) that deny `Read` access to a file also block uploading it. * **Size** : a single upload can include up to 10 MB of files in total. * **Hard links** : Claude refuses files that have multiple hard links, which is common inside package-manager stores like `node_modules`. Copy the file and upload the copy. + * **Credential names** : Claude refuses a file whose name or folder is one that credentials are kept under, such as `.env`, a `.pem` or `.key` file, or anything under `.ssh`. Requires Claude Code v2.1.293 or later. ### @@ -291,6 +289,22 @@ ​ +Project settings can’t turn on Chrome + +This warning in your terminal means the project you’re working in tried to turn on Chrome integration, and Claude Code didn’t allow it: + + Claude Code ignored CLAUDE_CODE_ENABLE_CFC in this project's settings: a project can't turn on Claude in Chrome. To turn it on yourself, run /chrome or start with --chrome. + +The project’s `.claude/settings.json` or `.claude/settings.local.json` sets [`CLAUDE_CODE_ENABLE_CFC`](</docs/en/env-vars#variables>) to `1` in its `env` block to turn Chrome integration on. Claude Code didn’t apply that setting, so Chrome integration is off in this session and Claude has no browser tools. Claude Code skips the setting because those files are stored in the project directory, and a repository you check out must not be able to connect Claude to your browser. You can keep working as you are. If you want browser tools, or want the warning gone, do one of these: + + * **To get browser tools now** : exit and start again with `claude --chrome` in your shell. + * **To get browser tools in later sessions** : run `/chrome` at the Claude Code prompt and select **Enabled by default**. This applies to sessions you start afterward, not the one that’s running. + * **To stop the warning without browser tools** : remove the `CLAUDE_CODE_ENABLE_CFC` line from the project’s settings file. + +### + +​ + Browser not responding If Claude’s browser commands stop working: @@ -305,7 +319,19 @@ Connection drops during long sessions -The Chrome extension’s service worker can go idle during extended sessions, which breaks the connection. If browser tools stop working after a period of inactivity, run `/chrome` and select “Reconnect extension”. +The Chrome extension’s service worker can go idle during extended sessions, which breaks the connection. If browser tools stop working after a period of inactivity, run `/chrome` and select “Reconnect extension”. When you run `/chrome`, check its `Status` line. If it reads “Not connected”, the running session’s own connection to Chrome has failed. Select “Reconnect extension” to restart that connection. After the connection succeeds, the extension’s reconnect page opens in Chrome. Before v2.1.290, “Reconnect extension” only opened that page and didn’t restart a failed connection, so if browser tools don’t return on an earlier version, update Claude Code. + +### + +​ + +Extension signed in to a different organization + +If you belong to more than one claude.ai organization, the extension must be signed in to the same organization as Claude Code. If the two differ, Claude’s browser tools return “Browser extension is not connected”, even when both use the same claude.ai account. To see which organization Claude Code is signed in to, run [`/status`](</docs/en/commands>) at the Claude Code prompt and read the `Organization` row. + +If you log out of the extension, you lose the shortcuts and scheduled tasks saved in it. Try the other fixes under Common error messages first. + +To change the extension’s organization, log out in the extension’s settings, then log in and select the organization that `/status` shows. ### @@ -329,7 +355,7 @@ Error| Cause| Fix ---|---|--- -”Browser extension is not connected”| Native messaging host cannot reach the extension, or your organization’s IP allowlist rejects the connection to `bridge.claudeusercontent.com`| Check that the extension is signed in to the same claude.ai account as Claude Code, restart Chrome and Claude Code, then run `/chrome` to reconnect. If your organization uses IP allowlisting and the error persists, see [Organization IP allowlists and proxy egress](</docs/en/network-config#organization-ip-allowlists-and-proxy-egress>) +”Browser extension is not connected”| The extension isn’t installed and running in Chrome, the extension is signed in to a different claude.ai account or organization than Claude Code, or your organization’s IP allowlist rejects the connection to `bridge.claudeusercontent.com`| Check that the extension is signed in to the same claude.ai account and organization as Claude Code, restart Chrome and Claude Code, then run `/chrome` to reconnect. If your organization uses IP allowlisting and the error persists, see [Organization IP allowlists and proxy egress](</docs/en/network-config#organization-ip-allowlists-and-proxy-egress>) Extension shows “Not detected” in `/chrome`| Chrome extension is not installed or is disabled| Install or enable the extension in `chrome://extensions` ”No tab available”| Claude tried to act before a tab was ready| Ask Claude to create a new tab and retry ”Receiving end does not exist”| Extension service worker went idle| Run `/chrome` and select “Reconnect extension”
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 @@ -217,7 +217,7 @@ Log a developer in -This last step happens on a developer machine, not the server. Set `forceLoginMethod` to `"gateway"` and `forceLoginGatewayUrl` to your gateway’s `public_url` in that machine’s [managed settings file](</docs/en/managed-settings#delivery-mechanisms>), then run `/login`, press Enter on the **Cloud gateway** screen, and complete the browser sign-in. Set the gateway URL below covers distributing both keys to every developer machine. +This last step happens on a developer machine, not the server. Set `forceLoginMethod` to `"gateway"`, `forceLoginGatewayUrl` to your gateway’s `public_url`, and `parentSettingsBehavior` to `"merge"` in that machine’s [managed settings file](</docs/en/managed-settings#delivery-mechanisms>), then run `/login`, press Enter on the **Cloud gateway** screen, and complete the browser sign-in. Set the gateway URL below covers the three keys and distributing them to every developer machine. ## @@ -284,7 +284,7 @@ Deliver policy to Claude Desktop sessions -Claude Desktop runs its Cowork and Code tabs, plus the Chat tab when you enable it, on embedded Claude Code sessions and sends their model requests through the gateway. It passes policy to each of those sessions, built from the configuration the gateway serves it at `/user/bootstrap`: the model allowlist, disabled tools, and egress allowlist derived from the matched policy’s `cli` block, plus the [`desktop` overlay](</docs/en/claude-apps-gateway-config#claude-desktop-overlay>). Other `cli` keys, such as hooks, `env`, and scoped permission rules like `Bash(npm *)`, reach only clients that sign in through `/login`. Claude Desktop reads the gateway URL from its own managed configuration and signs in with its own flow, separate from the `forceLoginMethod` and `forceLoginGatewayUrl` keys in Set the gateway URL. Settings passed by a launching process are parent settings. Claude Code ignores parent settings on any machine that has an admin-deployed managed source, unless the [source that delivers the policy](</docs/en/managed-settings#which-managed-source-claude-code-uses>) sets `parentSettingsBehavior: "merge"`. +Claude Desktop runs its Cowork and Code tabs, plus the Chat tab when you enable it, on embedded Claude Code sessions and sends their model requests through the gateway. It passes policy to each of those sessions, built from the configuration the gateway serves it at `/user/bootstrap`: the model allowlist, disabled tools, and egress allowlist derived from the matched policy’s `cli` or `code` block, plus the [`desktop` overlay](</docs/en/claude-apps-gateway-config#claude-desktop-overlay>). The block’s other keys, such as hooks, `env`, and scoped permission rules like `Bash(npm *)`, reach clients that sign in through `/login`. Under `code`, they also reach the Code tab’s session when the [conditions for the Code tab](</docs/en/claude-apps-gateway-config#apply-code-settings-in-the-code-tab>) hold. They don’t reach Cowork or Chat sessions. Claude Desktop reads the gateway URL from its own managed configuration and signs in with its own flow, separate from the `forceLoginMethod` and `forceLoginGatewayUrl` keys in Set the gateway URL. Settings passed by a launching process are parent settings. Claude Code ignores parent settings on any machine that has an admin-deployed managed source, unless the [source that delivers the policy](</docs/en/managed-settings#which-managed-source-claude-code-uses>) sets `parentSettingsBehavior: "merge"`. #### @@ -312,13 +312,13 @@ Mirror the snippet to any source that outranks the file -Claude Code reads `parentSettingsBehavior` only from the [selected source](</docs/en/managed-settings#which-managed-source-claude-code-uses>). Adding any policy key to a source can make that source the selected one, so in a client-side source, mirror the whole snippet rather than `parentSettingsBehavior` alone. [Client-side managed settings](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) covers fleets that deliver policy through Group Policy or configuration profiles. A managed-preferences plist on macOS or an HKLM policy on Windows outranks the `managed-settings.json` file, and the gateway’s own remote managed settings outrank both, so on machines that sign in to the gateway, also set `parentSettingsBehavior` in the gateway policy’s [`cli` block](</docs/en/claude-apps-gateway-config#managed>). +Claude Code reads `parentSettingsBehavior` only from the [selected source](</docs/en/managed-settings#which-managed-source-claude-code-uses>). Adding any policy key to a source can make that source the selected one, so in a client-side source, mirror the whole snippet rather than `parentSettingsBehavior` alone. [Client-side managed settings](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) covers fleets that deliver policy through Group Policy or configuration profiles. A managed-preferences plist on macOS or an HKLM policy on Windows outranks the `managed-settings.json` file, and the gateway’s own remote managed settings outrank both, so on machines that sign in to the gateway, also set `parentSettingsBehavior` in the gateway policy’s [`cli` or `code` block](</docs/en/claude-apps-gateway-config#managed>). 3 Check which source is selected -On a machine that only runs Claude Desktop, call the Agent SDK’s [`resolveSettings()`](</docs/en/agent-sdk/typescript#resolvesettings>) and read `policyOrigin` on the `managed` entry in its `sources` list. The value names the selected client-side source, `plist`, `hklm`, or `file`, which is the source that must carry the snippet. Claude Desktop’s embedded sessions don’t fetch the gateway policy, so the gateway’s `cli` block never counts as the selected source for them. +On a machine that only runs Claude Desktop, call the Agent SDK’s [`resolveSettings()`](</docs/en/agent-sdk/typescript#resolvesettings>) and read `policyOrigin` on the `managed` entry in its `sources` list. The value names the selected client-side source, `plist`, `hklm`, or `file`, which is the source that must carry the snippet.Cowork and Chat sessions don’t fetch the gateway policy, so the gateway’s block isn’t the selected source for them.A Code tab session fetches it when the policy’s settings are under `code` and the [conditions for the Code tab](</docs/en/claude-apps-gateway-config#apply-code-settings-in-the-code-tab>) hold. The gateway’s `code` settings are then the selected source for that session. ### @@ -362,7 +362,7 @@ } } -An OS policy, such as an HKLM registry policy or a managed-preferences plist, outranks this file, so deliver the whole snippet through it instead of the file. The gateway’s remote managed settings outrank the OS policy and file sources but reach only connected clients. Mirror the locks, the allowlists, and the merge opt-in into the policy’s [`cli` block](</docs/en/claude-apps-gateway-config#managed>) and keep this file deployed, because machines that never connect, including ones that only run Claude Desktop, get their policy from the file alone. +An OS policy, such as an HKLM registry policy or a managed-preferences plist, outranks this file, so deliver the whole snippet through it instead of the file. The gateway’s remote managed settings outrank the OS policy and file sources but reach only connected clients. Mirror the locks, the allowlists, and the merge opt-in into the policy’s [`cli` or `code` block](</docs/en/claude-apps-gateway-config#managed>) and keep this file deployed, because machines that never connect get their policy from the file alone. ####
modified Claude apps gateway configuration View current →
Show diff (114 lines)
--- a/claude-apps-gateway-config.md +++ b/claude-apps-gateway-config.md @@ -850,9 +850,36 @@ ​ +Choose `cli` or `code` + +When a policy uses the `code` key, each of these stops the gateway from starting: + + * **Gateway version** : `code` requires Claude Code v2.1.296 or later on the gateway server. An earlier gateway refuses to start when it finds the key. Upgrade every replica before you add the key, and change `code` back to `cli` before you roll back to an earlier version. + * **Mixed keys** : a file that has both `code` and `cli`, or its earlier spelling `settings`, stops the gateway at boot. Put every block under one key, in one edit. + +A policy’s Claude Code settings, such as a rule that denies reading `.env` files, go in a block under the `cli` or `code` key. `code` is the recommended key, and `cli` is the legacy key. Both keys take the same contents. The key decides where the settings are enforced: + + * **`cli`** : the terminal, the VS Code and JetBrains extensions, and the Agent SDK. Under `cli`, Claude Desktop’s Code tab gets the derived settings, so a scoped rule such as `Read(./.env)` doesn’t stop a user there. + * **`code`** : the same places, and Claude Desktop’s Code tab can be covered too. + +A file that uses `cli` works as it did, and a gateway that finds `cli` in a policy with a `desktop` key warns at boot and starts anyway. Switch to `code` so that the settings can also cover the Code tab. Before you switch, read Apply `code` settings in the Code tab. The policy needs a `desktop` key and users’ machines need setup before the settings apply there, and web search turns off in Claude Desktop. This policy puts the deny rule under `code`, with an empty `desktop` key: + + managed: + policies: + - match: {} + code: + permissions: { deny: ["Read(./.env)"] } + desktop: {} + +When you switch, delete any `serve_to_desktop` line in the same edit that renames the blocks. Where an instruction names the `cli` block, use your `code` block. + +#### + +​ + What goes in `cli` -Each `cli` value is a complete Claude Code `managed-settings.json` document, the same schema you would deploy via MDM or `/etc/claude-code/managed-settings.json`, expressed here as YAML. The CLI applies the delivered document at the managed tier, above user and project settings, in place of server-managed settings. It therefore ignores the settings [restricted to OS-level policy sources](</docs/en/server-managed-settings#current-limitations>), such as `policyHelper` and `wslInheritsWindowsSettings`. The gateway validates each document against the CLI’s settings schema at boot, so an unrecognized top-level key fails boot with an error naming every offending key. Deliberately open parts of the schema still accept arbitrary values, because newer clients may recognize entries the gateway’s schema doesn’t. These open keys include `env`, `pluginConfigs`, and keys nested under `permissions`. Because validation uses the schema bundled with the gateway’s installed version, putting a top-level settings key introduced by a newer Claude Code release into managed config requires upgrading the gateway first. Smoke-test a new policy on one client before rolling it out. The full key reference is in [Claude Code settings](</docs/en/settings-reference#all-settings>). The keys most operators reach for first: +Each `code` or `cli` value is a complete Claude Code `managed-settings.json` document, the same schema you would deploy via MDM or `/etc/claude-code/managed-settings.json`, expressed here as YAML. The CLI applies the delivered document at the managed tier, above user and project settings, in place of server-managed settings. It therefore ignores the settings [restricted to OS-level policy sources](</docs/en/server-managed-settings#current-limitations>), such as `policyHelper` and `wslInheritsWindowsSettings`. The gateway validates each document against the CLI’s settings schema at boot, so an unrecognized top-level key fails boot with an error naming every offending key. Deliberately open parts of the schema still accept arbitrary values, because newer clients may recognize entries the gateway’s schema doesn’t. These open keys include `env`, `pluginConfigs`, and keys nested under `permissions`. Because validation uses the schema bundled with the gateway’s installed version, putting a top-level settings key introduced by a newer Claude Code release into managed config requires upgrading the gateway first. Smoke-test a new policy on one client before rolling it out. The full key reference is in [Claude Code settings](</docs/en/settings-reference#all-settings>). The keys most operators reach for first: managed: policies: @@ -903,7 +930,7 @@ * the sandbox binary settings `sandbox.bwrapPath`, `sandbox.socatPath`, and `sandbox.ripgrep` * Sandbox settings that intercept traffic, inject credentials, or weaken isolation, such as `sandbox.network.tlsTerminate` and the proxy port settings. [Security approval dialogs](</docs/en/server-managed-settings#security-approval-dialogs>) lists them all. -[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](</docs/en/server-managed-settings#security-approval-dialogs>), such as `claude -p` or an Agent SDK session, 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 that session rather than applying the policy. When you push a new hook, or any env var that triggers the dialog, to a broad policy, every matching developer therefore sees the dialog in their interactive sessions. A running interactive session shows it on the next hourly poll, and otherwise it appears at the developer’s next interactive 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](</docs/en/server-managed-settings#security-approval-dialogs>), such as `claude -p`, an Agent SDK session, or a session in Claude Desktop’s Code tab, 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 that session rather than applying the policy. When you push a new hook, or any env var that triggers the dialog, to a broad policy, every matching developer therefore sees the dialog in their interactive sessions. A running interactive session shows it on the next hourly poll, and otherwise it appears at the developer’s next interactive startup. The `cli` key was named `settings` in earlier releases, and the gateway still accepts that spelling as an alias. For new deployments, use `code`. #### @@ -944,7 +971,7 @@ ##### Settings the gateway derives for Claude Desktop -The gateway derives much of the bootstrap response from the matched policy’s `cli` block and from top-level gateway config: +The gateway derives much of the bootstrap response from the matched policy’s `cli` or `code` block and from top-level gateway config: * The model list, from `availableModels`. Extended context in Claude Desktop covers each model’s 1M context option * Disabled tools, from bare tool-name `permissions.deny` entries. If you set `disabledBuiltinTools` in the policy’s `desktop` block, the gateway serves the union of your value and the derived list, so you can disable more tools this way but can’t re-enable one you disabled through `permissions.deny` @@ -952,6 +979,23 @@ * An OTLP endpoint that points at the gateway itself, and the signed-in user’s identity attributes. The gateway relays the exports it receives at that endpoint to your `forward_to` destinations. It includes the endpoint and the attributes when you set both `telemetry.forward_to` and `listen.public_url`. Claude Desktop exports every signal with one encoding: `http/protobuf`, or `http/json` when you set `OTEL_EXPORTER_OTLP_PROTOCOL` or one of its per-signal variants to `http/json` in the policy’s `env`. Before Claude Code v2.1.261 on the gateway server, the response set `http/json` regardless, so a collector that accepts only protobuf rejected Claude Desktop’s exports To set `disabledBuiltinTools`, `coworkEgressAllowedHosts`, or Claude Desktop’s own `managedMcpServers` setting in a policy’s `desktop` block, you need Claude Code v2.1.232 or later on the gateway server. Claude Desktop’s `managedMcpServers` takes an array value rather than an object. The gateway omits keys with no Claude Desktop equivalent, such as `hooks` and scoped permission rules like `Bash(npm *)`, from the bootstrap response. + +##### Apply `code` settings in the Code tab + +The Claude Code settings a policy holds under its `code` key apply in Claude Desktop’s Code tab when all of these hold: + + * The policy also has a `desktop` key, and an empty `desktop: {}` counts + * Claude Desktop is version 2.9939.2 or later + * The Claude Code managed settings on the machine name this gateway + * That machine reaches the gateway over HTTPS on a private network + +The last two conditions apply to whichever machine runs Claude Code for the session. For a local session, that is the user’s own computer. For a Code tab session over SSH, it is the remote host. Deploy the client-side managed settings to those machines before you rename `cli` to `code`. When the first two conditions hold and either of the last two fails, a user the policy matches gets one of these results: + + * **Over HTTPS, where Claude Desktop bundles Claude Code v2.1.296 or later** : the Code tab doesn’t start, and the reply to the user’s prompt says why + * **Over HTTPS, where Claude Desktop bundles an earlier version** : the Code tab starts without your `code` settings, and nothing in the session says so + * **Over plain HTTP** : the Code tab starts without your `code` settings, whichever version Claude Desktop bundles + +When a proxy in front of the gateway answers `/managed/settings` with its own 404, the Code tab also starts without your `code` settings, including on a machine that meets all four conditions. In a policy that has a `desktop` key, a `code` block that holds settings turns off the WebSearch tool in Cowork, Chat, and the Code tab. For MCP servers, see [Where `managedMcpServers` applies](</docs/en/managed-mcp#where-managedmcpservers-applies>). ##### Set Claude Desktop settings directly @@ -1053,7 +1097,7 @@ `telemetry` -The CLI sends metrics, logs, and, when enabled, traces to the gateway, which relays them verbatim to each configured destination. The exports use OpenTelemetry Protocol (OTLP) over HTTP. To skip the relay and have sessions export straight to your collector, name the collector in a policy. See [Monitoring usage](</docs/en/monitoring-usage>) for the metrics and events the CLI emits. In sessions signed in through `/login`, the CLI stamps each export with the authenticated user’s identity, read from the gateway-issued JWT: the `user.id`, `user.email`, and `user.groups` attributes. Per-developer cost and usage attribution therefore works with no developer-side configuration. Events that Claude Code logs before the developer signs in [don’t carry this identity](</docs/en/monitoring-usage#standard-attributes>). Claude Desktop and Cowork sessions signed in through the gateway stamp their telemetry with `user.email` and `user.groups` alongside `enduser.id`, so you can cover terminal, Desktop, and Cowork usage with one query on `user.email` or `user.groups`. `user.groups` is the comma-separated IdP group list. Desktop and Cowork telemetry also carries `enduser.sub`, the `sub` claim your identity provider issues for the user, which stays the same when a user’s email changes. Terminal sessions stamp the same value under `user.id`, so a query that matches `enduser.sub` against terminal `user.id` covers one user’s terminal, Desktop, and Cowork usage together. On Desktop and Cowork exports, `user.id` is an anonymous identifier, not the subject. Like all OpenTelemetry data from Claude Code, these attributes go only to destinations your organization configures, never to Anthropic. If a user’s group list is longer than 255 characters once percent-encoded, or a group name contains a comma or equals sign, the gateway leaves `user.groups` off that user’s Desktop and Cowork telemetry rather than truncating it. That user’s terminal sessions still carry the full list. The gateway leaves `enduser.sub` off when the subject is longer than 255 characters once percent-encoded, or contains a space, a character outside printable ASCII, or one of `,` `;` `=` `\` `"` `%`. That user’s Desktop and Cowork telemetry keeps its other attributes. You need Claude Code v2.1.265 or later on the gateway server for `user.email` and `user.groups` on Desktop and Cowork telemetry, and Claude Desktop 1.24012 or later on each developer’s machine for `user.groups`. You need Claude Code v2.1.274 or later on the gateway server for `enduser.sub`. +The CLI sends metrics, logs, and, when enabled, traces to the gateway, which relays them verbatim to each configured destination. The exports use OpenTelemetry Protocol (OTLP) over HTTP. To skip the relay and have sessions export straight to your collector, name the collector in a policy. See [Monitoring usage](</docs/en/monitoring-usage>) for the metrics and events the CLI emits. In sessions signed in through `/login`, the CLI stamps each export with the authenticated user’s identity, read from the gateway-issued JWT: the `user.id`, `user.email`, and `user.groups` attributes. Per-developer cost and usage attribution therefore works with no developer-side configuration. Events that Claude Code logs before the developer signs in [don’t carry this identity](</docs/en/monitoring-usage#standard-attributes>). To see which attribute follows a change in a developer’s groups, see Group changes during an open session. Claude Desktop and Cowork sessions signed in through the gateway stamp their telemetry with `user.email` and `user.groups` alongside `enduser.id`, so you can cover terminal, Desktop, and Cowork usage with one query on `user.email` or `user.groups`. `user.groups` is the comma-separated IdP group list. Desktop and Cowork telemetry also carries `enduser.sub`, the `sub` claim your identity provider issues for the user, which stays the same when a user’s email changes. Terminal sessions stamp the same value under `user.id`, so a query that matches `enduser.sub` against terminal `user.id` covers one user’s terminal, Desktop, and Cowork usage together. On Desktop and Cowork exports, `user.id` is an anonymous identifier, not the subject. Like all OpenTelemetry data from Claude Code, these attributes go only to destinations your organization configures, never to Anthropic. If a user’s group list is longer than 255 characters once percent-encoded, or a group name contains a comma or equals sign, the gateway leaves `user.groups` off that user’s Desktop and Cowork telemetry rather than truncating it. That user’s terminal sessions still carry the full list. The gateway leaves `enduser.sub` off when the subject is longer than 255 characters once percent-encoded, or contains a space, a character outside printable ASCII, or one of `,` `;` `=` `\` `"` `%`. That user’s Desktop and Cowork telemetry keeps its other attributes. You need Claude Code v2.1.265 or later on the gateway server for `user.email` and `user.groups` on Desktop and Cowork telemetry, and Claude Desktop 1.24012 or later on each developer’s machine for `user.groups`. You need Claude Code v2.1.274 or later on the gateway server for `enduser.sub`. telemetry: forward_to: @@ -1118,6 +1162,22 @@ * Values are text, so quote a number, `true`, or `false` You need Claude Code v2.1.281 or later on the gateway server to set `telemetry.resource_attributes`. An earlier gateway refuses to start when it finds the key. Upgrade every replica before you add the key, and remove the key before you roll back to an earlier version. Terminal sessions signed in through `/login` receive the labels as `OTEL_RESOURCE_ATTRIBUTES`, pushed with the other telemetry variables. If you set `OTEL_RESOURCE_ATTRIBUTES` in a policy’s `env` block, terminal sessions that policy matches get that value instead of the labels. Claude Desktop receives the labels from the gateway alongside `user.email` and the other identity attributes. Claude Code also copies each label onto every metric data point, so you can filter metrics by it in a backend that doesn’t index resource attributes. To turn that copy off, see [Metrics cardinality control](</docs/en/monitoring-usage#metrics-cardinality-control>). + +#### + +​ + +Group changes during an open session + +Terminal sessions put `user.groups` on the OTLP resource and again on each metric data point and event. If a developer’s groups change while a session is open, data points and events for usage after the next silent refresh carry the new groups. The resource keeps the old groups until the developer restarts Claude Code, so group by the attribute on the data point or event. If you turn on `resource_to_telemetry_conversion` in the OpenTelemetry Collector’s Prometheus remote write exporter, the exporter replaces each data point’s `user.groups` with the resource’s, so every data point shows the old groups. To keep the data point’s value, delete `user.groups` from the resource ahead of that exporter. This OpenTelemetry Collector `resource` processor deletes the attribute in the pipelines that list it: + + processors: + resource/drop-user-groups: + attributes: + - key: user.groups + action: delete + +After you add `resource/drop-user-groups` to the metrics pipeline’s `processors`, each series carries the `user_groups` label from its own data point. ####
modified Claude apps gateway deployment and operations View current →
--- a/claude-apps-gateway-deploy.md +++ b/claude-apps-gateway-deploy.md @@ -339,7 +339,7 @@ * **A marketplace list** : a [`strictKnownMarketplaces`](</docs/en/plugins/org#allowlist-with-strictknownmarketplaces>) allowlist that leaves the marketplace out, or a [`blockedMarketplaces`](</docs/en/plugins/org#blocklist-with-blockedmarketplaces>) entry that names it * **An environment variable** : `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` set to `"1"` in the managed [`env` block](</docs/en/plugins/org#turn-updates-off-for-the-whole-fleet>) -The first registration can run before the developer signs in to the gateway, when no gateway policy has arrived. To cover that first start, deliver your choice in [client-side managed settings](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) as well as in the gateway policy’s [`cli` block](</docs/en/claude-apps-gateway-config#what-goes-in-cli>). +The first registration can run before the developer signs in to the gateway, when no gateway policy has arrived. To cover that first start, deliver your choice in [client-side managed settings](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) as well as in the gateway policy’s [`cli` or `code` block](</docs/en/claude-apps-gateway-config#what-goes-in-cli>). ##
modified Deploy Claude apps gateway on AWS View current →
--- a/claude-apps-gateway-on-aws.md +++ b/claude-apps-gateway-on-aws.md @@ -410,7 +410,7 @@ Push the gateway URL to developer machines -The gateway is now running, but developers can’t reach it from `/login` until the gateway URL is on their machines. Set `forceLoginMethod` and `forceLoginGatewayUrl` in the [managed settings file](</docs/en/claude-apps-gateway#set-the-gateway-url>) you deploy to each device via MDM. There is no gateway option in the login picker for a developer to select manually. +The gateway is now running, but developers can’t reach it from `/login` until the gateway URL is on their machines. Deploy the full [managed settings snippet](</docs/en/claude-apps-gateway#set-the-gateway-url>), with `forceLoginMethod`, `forceLoginGatewayUrl`, and the `parentSettingsBehavior: "merge"` opt-in, to each device via MDM. There is no gateway option in the login picker for a developer to select manually. ##
modified Use Claude Code in the cloud View current →
--- a/claude-code-on-the-web.md +++ b/claude-code-on-the-web.md @@ -79,7 +79,7 @@ ​ -From terminal to cloud +Start a cloud session from your terminal Start a cloud session from the command line with the `--cloud` flag: @@ -177,7 +177,7 @@ ​ -From cloud to terminal +Continue a cloud session in your terminal Pull a cloud session into your terminal using any of these: @@ -455,7 +455,7 @@ Cloud sessions stop after a period of inactivity and the session’s VM is reclaimed. A session counts as inactive while it waits for you to approve an [MCP connector](</docs/en/cloud-environments#network-access>) tool call or to sign in to an MCP server, and it can expire during that wait. Reopen the session from [claude.ai/code](<https://claude.ai/code>) to provision a fresh VM: * **Restored** : your conversation history - * **Not restored** : background work that was still running when the VM was reclaimed, such as subagents and shell commands + * **Not restored** : background work that was still running when the VM was reclaimed, such as subagents and shell commands, and the pending wakeup of a [self-paced `/loop`](</docs/en/scheduled-tasks#let-claude-choose-the-interval>). To restart the loop, run `/loop` again. ##
modified Let Claude coordinate ongoing work with Projects View current →
--- a/claude-projects.md +++ b/claude-projects.md @@ -285,7 +285,11 @@ Unblock a thread waiting on approval -Threads run in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) when the thread’s model supports it, so most tool calls run without asking you. When a thread needs your approval, the prompt is inside that thread and the thread waits until you answer it there. Telling Claude in the project conversation to go ahead doesn’t reach it. Each approval covers that prompt, or the rest of that thread if you choose the broader option. To let every thread run certain commands without asking, or to block some, add [permission rules](</docs/en/permissions>) to the repository’s `.claude/settings.json`. Cloud threads apply them only in a project with one repository; see What threads pick up from your repositories. In a project with several repositories, no repository’s permission rules reach a cloud thread, so you rely on auto mode and on the approvals you give inside each thread. +Threads run in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) when the thread’s model supports it, so most tool calls run without asking you. When a thread needs your approval, the prompt is inside that thread and the thread waits until you answer it there. Telling Claude in the project conversation to go ahead doesn’t reach it. Each approval covers that prompt, or the rest of that thread if you choose the broader option. To let every thread run certain commands without asking, or to block some, add [permission rules](</docs/en/permissions>) to the repository’s `.claude/settings.json`. Check that cloud threads in your project apply them: + + * **One repository** : cloud threads apply the rules. See What threads pick up from your repositories. + * **Several repositories, Anthropic-hosted environment** : no repository’s permission rules reach a cloud thread, so you rely on auto mode and on the approvals you give inside each thread. + * **Several repositories, self-hosted environment** : see [which repository’s settings apply](</docs/en/self-hosted-environments-configuration#repository-settings-in-sessions-with-several-repositories>). ### @@ -395,16 +399,16 @@ What threads pick up from your repositories -Each cloud thread clones every repository in the project and loads `CLAUDE.md` and skills from all of them. Permission rules, hooks, and `env` come only from the `.claude/settings.json` in the directory the thread starts in: inside the repository when the project has one, and above the clones when it has several, where no repository’s file is read for them. +Each cloud thread clones every repository in the project and loads `CLAUDE.md` and skills from all of them. Permission rules, hooks, and `env` come only from the `.claude/settings.json` in the directory the thread starts in. In each repository| One repository| Several repositories ---|---|--- `CLAUDE.md`| Loaded when the thread starts| Loaded from every repository when the thread starts Skills, agents, and commands under `.claude/`| Loaded| Loaded from every repository Plugins enabled in `.claude/settings.json`| Not loaded. Add the plugin in **Project settings > Plugins** instead| Not loaded. Add the plugin in **Project settings > Plugins** instead -Permission rules, hooks, and `env` defined in `.claude/settings.json`| Apply to the thread, except the `env` keys that [no cloud session honors](</docs/en/cloud-environments#what-carries-over-from-your-setup>)| Don’t apply - -In a project with several repositories, each clone is attached to the thread as an [additional directory](</docs/en/memory#load-from-additional-directories>) with `CLAUDE.md` loading turned on, which is why every repository’s `CLAUDE.md` and skills load at start even though the thread starts above them. In such a project, put standing rules in project instructions and give threads environment variables through the cloud environment. +Permission rules, hooks, and `env` defined in `.claude/settings.json`| Apply to the thread, except the `env` keys that [no cloud session honors](</docs/en/cloud-environments#what-carries-over-from-your-setup>)| Don’t apply in an Anthropic-hosted environment. For a self-hosted environment, see [which repository’s settings apply](</docs/en/self-hosted-environments-configuration#repository-settings-in-sessions-with-several-repositories>) + +In a project with several repositories, put standing rules in project instructions and give threads environment variables through the cloud environment. ### @@ -422,7 +426,7 @@ Cloud threads don’t have the skills, MCP servers, plugins, and tools installed only on your machine. A thread that Claude runs on your machine through [Remote Control](</docs/en/remote-control>) uses what’s installed there. To make each of these available to cloud threads: - * Skills, subagents, and commands: commit them to a repository you added to the project, for example a skill at `.claude/skills/<skill-name>/SKILL.md`. Each cloud thread clones every repository in the project and loads `.claude/skills/`, `.claude/agents/`, and `.claude/commands/` from each of them, so a skill committed to one repository is available in every cloud thread. Cloud threads also load the skills you enable for your claude.ai account. + * Skills, subagents, and commands: commit them to a repository you added to the project, for example a skill at `.claude/skills/<skill-name>/SKILL.md`. Each cloud thread clones every repository in the project and loads `.claude/skills/`, `.claude/agents/`, and `.claude/commands/` from each of them, so a skill committed to one repository is available in every cloud thread. Cloud threads also load the [skills you enable for your claude.ai account](</docs/en/skills#skills-in-cowork-and-cloud-sessions>). * Plugins: add them in **Project settings > Plugins**; they load into each new cloud thread. Plugins that a repository declares in its `.claude/settings.json` [don’t load in cloud threads](</docs/en/cloud-environments#what-carries-over-from-your-setup>). * MCP servers: cloud threads get their MCP tools from the connectors on your claude.ai account, which are MCP servers you connect once at [claude.ai/customize/connectors](<https://claude.ai/customize/connectors>) or through the **Manage connectors** link in **Project settings > Environment**. Every cloud thread can use all of them with no per-project setup. The project conversation itself has no connectors, so send work that needs one as a task for a cloud thread. In a project with one repository, cloud threads also load MCP servers from that repository’s [`.mcp.json`](</docs/en/cloud-environments#what-carries-over-from-your-setup>). [How connectors reach Claude Code](</docs/en/mcp#how-connectors-reach-claude-code>) lists the rules for cloud sessions and the settings that turn connectors off. * Command-line tools and packages: install them in the environment’s [setup script](</docs/en/cloud-environments#setup-scripts>).
modified CLI reference View current →
--- a/cli-reference.md +++ b/cli-reference.md @@ -22,7 +22,7 @@ `claude auth logout`| Log out from your Anthropic account| `claude auth logout` `claude auth status`| Show authentication status as JSON. Use `--text` for human-readable output. Exits with code 0 if logged in, 1 if not. The JSON includes a `configDirectory` field naming the [configuration directory](</docs/en/claude-directory>) the CLI uses. The field requires Claude Code v2.1.268 or later. The JSON’s `authMethod` field is one of `none`, `claude.ai`, `oauth_token`, `api_key`, `api_key_helper`, or `third_party`| `claude auth status` `claude agents`| Open [agent view](</docs/en/agent-view>) to monitor and dispatch parallel background sessions. Use `--cwd <path>` to show only sessions started under that directory, or `--json` to print active sessions as a JSON array for scripting (`--json --all` also includes completed background sessions). Pass `--permission-mode`, `--model`, `--effort`, or `--agent` to set [defaults for dispatched sessions](</docs/en/agent-view#permission-mode-model-and-effort>). Accepts `--settings`, `--add-dir`, `--plugin-dir`, and `--mcp-config` like the top-level `claude` command. Opening agent view requires an interactive terminal| `claude agents --json` -`claude attach <id|name>`| Attach to a [background session](</docs/en/agent-view#manage-sessions-from-the-shell>) in this terminal. Passing part of a running session’s name in place of the ID requires Claude Code v2.1.290 or later| `claude attach 7c5dcf5d` +`claude attach <id|name>`| Attach to a [background session](</docs/en/agent-view#manage-sessions-from-the-shell>) in this terminal. Passing part of a session’s name in place of the ID requires Claude Code v2.1.290 or later| `claude attach 7c5dcf5d` `claude auto-mode defaults`| Print the built-in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier rules as JSON. Use `claude auto-mode config` to see your effective config with settings applied. `--label <prefix>` prints only the rules whose label starts with that prefix, matched case-insensitively. Requires Claude Code v2.1.208 or later| `claude auto-mode defaults --label 'Git Destructive'` `claude auto-mode reset`| Restore the default [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) configuration by removing the `autoMode` section from your user settings file. Prompts for confirmation before writing; pass `-y`/`--yes` to skip the prompt. Rules from [managed settings](</docs/en/server-managed-settings>) or the `--settings` flag still apply. Requires Claude Code v2.1.212 or later. See [Inspect the defaults and your effective config](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>)| `claude auto-mode reset --yes` `claude daemon logs`| Follow the background-session [supervisor’s](</docs/en/agent-view#the-supervisor-process>) log file, `~/.claude/daemon.log`, printing new lines as they arrive until you press `Ctrl+C`| `claude daemon logs` @@ -31,9 +31,9 @@ `claude daemon stop --any`| Stop the background-session [supervisor](</docs/en/agent-view#the-supervisor-process>) and the sessions it hosts. Pass `--keep-workers` to leave background sessions running so the next supervisor reconnects to them. `--any` confirms stopping an on-demand supervisor, which is the default. Use this to recover from an [unresponsive supervisor](</docs/en/agent-view#agent-view-says-the-background-service-did-not-respond>)| `claude daemon stop --any --keep-workers` `claude doctor`| Print read-only installation and settings diagnostics from the terminal without starting a session, including install health, settings-file validation errors, and Remote Control eligibility. For the in-session setup checkup that can also apply fixes, run [`/doctor`](</docs/en/commands#all-commands>)| `claude doctor` `claude import [source]`| Start an interactive session that runs [`/import`](</docs/en/commands#all-commands>) to bring configuration from other coding agents into Claude Code. Accepts the same `--dry-run` and `--yes` options as the command. Not available on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or Claude Platform on AWS. Also unavailable when you turn off [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>). Requires Claude Code v2.1.213 or later| `claude import codex --dry-run` -`claude logs <id|name>`| Print recent output from a [background session](</docs/en/agent-view#manage-sessions-from-the-shell>). Passing part of a running session’s name in place of the ID requires Claude Code v2.1.290 or later| `claude logs 7c5dcf5d` +`claude logs <id|name>`| Print recent output from a [background session](</docs/en/agent-view#manage-sessions-from-the-shell>). Passing part of a session’s name in place of the ID requires Claude Code v2.1.290 or later| `claude logs 7c5dcf5d` `claude mcp`| Configure Model Context Protocol (MCP) servers| See the [Claude Code MCP documentation](</docs/en/mcp>). -`claude mcp login <name>`| Run a configured MCP server’s OAuth flow without opening the interactive `/mcp` panel. Works for HTTP, SSE, and claude.ai connector servers. Add `--no-browser` over SSH to print the authorization URL instead of opening a browser, then paste the redirect URL back at the prompt. See [Authenticate from the command line](</docs/en/mcp#authenticate-from-the-command-line>)| `claude mcp login sentry` +`claude mcp login <name>`| Run a configured MCP server’s OAuth flow without opening the interactive `/mcp` panel. Works for HTTP, SSE, and claude.ai connector servers. Add `--no-browser` over SSH to print the authorization URL instead of opening a browser. For an HTTP or SSE server, paste the redirect URL back at the prompt. For a claude.ai connector, see [Authorize a connector again from your shell](</docs/en/remote-control#authorize-a-connector-again-from-your-shell>). See [Authenticate from the command line](</docs/en/mcp#authenticate-from-the-command-line>)| `claude mcp login sentry` `claude mcp logout <name>`| Clear stored OAuth credentials for an MCP server| `claude mcp logout sentry` `claude plugin`| Manage Claude Code [plugins](</docs/en/plugins/overview>). Alias: `claude plugins`. See [plugin reference](</docs/en/plugins/cli-reference#claude-plugin-commands>) for subcommands| `claude plugin install code-review@claude-plugins-official` `claude purge [path]`| Delete all local Claude Code state for a project: transcripts, task lists, debug logs, file-edit history, prompt history lines, and the project’s entry in `~/.claude.json`. Omit `[path]` to pick from an interactive list. Flags: `--dry-run` to preview, `-y`/`--yes` to skip confirmation, `-i`/`--interactive` to confirm each item, `--all` for every project. See [Clear local data](</docs/en/claude-directory#clear-local-data>)| `claude purge ~/work/repo --dry-run` @@ -102,7 +102,7 @@ `--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`| Stop the run once estimated spend on API calls reaches this amount (print mode only). Claude Code checks the cap against its [client-side cost estimate](</docs/en/agent-sdk/cost-tracking#estimates-not-billing>), which can differ from your bill. Spend from [subagents](</docs/en/sub-agents>) counts toward the cap. Spend can pass the cap, so [leave headroom](</docs/en/agent-sdk/agent-loop#budget-headroom>). When you return to a conversation with `--continue` or `--resume`, totals [restored from earlier runs](</docs/en/agent-sdk/cost-tracking#accumulate-costs-across-multiple-calls>) don’t count toward it. 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 still queued when the limit ends a turn stays queued and starts a new turn with its own limit| `claude -p --max-turns 3 "query"` -`--mcp-config`| Load MCP servers from JSON files or strings (space-separated). When you pass this flag with `-p`, Claude Code waits for still-pending servers to connect before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default; a server with a [cached tool list](</docs/en/mcp#managing-your-servers>) skips the wait and connects on first use. The wait requires Claude Code v2.1.221 or later| `claude --mcp-config ./mcp.json` +`--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. In a [self-hosted environment](</docs/en/self-hosted-environments-configuration#connection-timing>), a shorter wait applies instead. The wait requires Claude Code v2.1.221 or later| `claude --mcp-config ./mcp.json` `--model`| Sets the model for the current session with a [model alias](</docs/en/model-config#model-aliases>) such as `sonnet`, `opus`, `haiku`, or `fable`, or a model’s full name. Overrides the [`model`](</docs/en/settings-reference#model>) setting and [`ANTHROPIC_MODEL`](</docs/en/model-config#environment-variables>)| `claude --model claude-sonnet-5` `--name`, `-n`| Set a display name for the session, shown in `/resume` and the terminal title. You can resume a named session with `claude --resume <name>`. In an interactive session, if another live session on this machine already uses the name, Claude Code applies [a variant of it](</docs/en/sessions#name-your-sessions>) instead.
modified Configure cloud environments View current →
--- a/cloud-environments.md +++ b/cloud-environments.md @@ -296,7 +296,7 @@ Plugins and marketplaces declared in your repo’s `.claude/settings.json`| No| A cloud session doesn’t install the plugins a repository turns on under [`enabledPlugins`](</docs/en/settings-reference#enabledplugins>), including ones from the marketplaces it lists under [`extraKnownMarketplaces`](</docs/en/settings-reference#extraknownmarketplaces>) Your organization’s [server-managed settings](</docs/en/server-managed-settings>)| Yes, except in [Claude Tag](<https://claude.com/docs/claude-tag/overview>) sessions| Fetched from Anthropic’s servers when the session starts. See [Surface coverage](</docs/en/model-config#surface-coverage>) for how `availableModels` is enforced in cloud sessions. Settings deployed to your device through MDM or managed settings files don’t apply, because the session runs on an Anthropic-managed VM; in a [self-hosted environment](</docs/en/self-hosted-environments>), sessions also read the managed settings file in the runner image, per [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) Your user `~/.claude/CLAUDE.md`| No| Lives on your machine, not in the repo. See Add personal preferences without committing to the repo -Your user `~/.claude/skills/`, `~/.claude/agents/`, `~/.claude/commands/`| No| Live on your machine, not in the repo. Commit them to the repo’s `.claude/` directory instead. Cloud sessions automatically load skills you enable on claude.ai +Your user `~/.claude/skills/`, `~/.claude/agents/`, `~/.claude/commands/`| No| Live on your machine, not in the repo. Commit them to the repo’s `.claude/` directory instead. Cloud sessions automatically load [skills you enable on claude.ai](</docs/en/skills#skills-in-cowork-and-cloud-sessions>) Plugins enabled only in your user settings| No| User-scoped `enabledPlugins` lives in `~/.claude/settings.json` on your machine MCP servers you added with `claude mcp add` at the default local scope or the user scope| No| Those write to `~/.claude.json` on your machine, not the repo. Add the server with `claude mcp add --scope project`, which writes the repo’s [`.mcp.json`](</docs/en/mcp#project-scope>), and commit that file. A session with one repository loads it Transport variables in your repo’s `.claude/settings.json` `env` block, such as `NODE_EXTRA_CA_CERTS` and the [mTLS client certificate variables](</docs/en/network-config#mtls-authentication>)| No| The hosting environment manages the session’s API connection, so Claude Code ignores these keys and notes each ignored key in the session’s debug log
modified Commands View current →
--- a/commands.md +++ b/commands.md @@ -85,7 +85,7 @@ `/login`| Sign in to your Anthropic account `/logout`| Sign out from your Anthropic account `/loop [interval] [prompt]`| **[Skill](</docs/en/skills#bundled-skills>).** Run a prompt repeatedly while the session stays open. Omit the interval and Claude [self-paces between iterations](</docs/en/scheduled-tasks#let-claude-choose-the-interval>). Omit the prompt and Claude runs the [built-in maintenance prompt](</docs/en/scheduled-tasks#run-the-built-in-maintenance-prompt>) or your [`loop.md`](</docs/en/scheduled-tasks#customize-the-default-prompt-with-loop-md>). Example: `/loop 5m check if the deploy finished`. See [Run prompts on a schedule](</docs/en/scheduled-tasks>). Alias: `/proactive` -`/mcp [reconnect (<server>|all)|enable|disable [<server>|all]]`| Manage MCP server connections and OAuth authentication. Run with no argument to open the interactive list, or pass `reconnect`, `enable`, or `disable` with a server name or `all` to change connection state without opening it. `reconnect all` [retries every server that failed or needs authentication](</docs/en/mcp#retry-failed-servers-yourself>). 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 +`/mcp [reconnect (<server>|all)|enable|disable [<server>|all]]`| Manage MCP server connections and OAuth authentication. Run with no argument to open the interactive list, or pass `reconnect`, `enable`, or `disable` with a server name or `all` to change connection state without opening it. `reconnect all` [retries every server that failed or needs authentication](</docs/en/mcp#retry-failed-servers-yourself>). In non-interactive mode (`-p`), running it with no argument prints a text summary of server status instead of opening the list; requires Claude Code v2.1.205 or later `/memory`| Edit `CLAUDE.md` files, enable or disable [auto memory](</docs/en/memory#auto-memory>), and view auto memory entries `/mobile`| Show QR code to download the Claude mobile app. Aliases: `/ios`, `/android` `/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. See [when Claude Code asks you to confirm the switch](</docs/en/prompt-caching#switching-models>). Once you confirm the switch, if Claude Code asks, Claude Code applies the change without waiting for the current response to finish. Before v2.1.242, Claude Code decided from a feature flag it fetched from Anthropic whether to run the command mid-turn or queue it until the turn finished, and always queued it in a session that doesn’t [fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), such as on a [third-party provider](</docs/en/third-party-integrations>). 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
modified Create a Claude Code plugin View current →
--- a/create.md +++ b/create.md @@ -171,7 +171,7 @@ ​ -From a directory or `.zip` +Load a plugin from a directory or `.zip` When you start `claude` from your shell, pass `--plugin-dir` with the plugin’s root directory or a `.zip` archive of it. Repeat the flag to load several plugins: @@ -181,7 +181,7 @@ ​ -From a folder of plugins +Load a folder of plugins To load several plugins from one place, pass a folder that holds them, such as `--plugin-dir ./plugins`. Loading a folder of plugins requires Claude Code v2.1.265 or later. If the folder has no `.claude-plugin/` directory and no plugin components at its top level, Claude Code treats it as a folder of plugins. Each immediate subfolder that has a `.claude-plugin/plugin.json` manifest then loads as a separate plugin. Everything else in the folder is skipped without an error, including a subfolder that has no manifest. If a plugin in the folder doesn’t load, check that its subfolder has a `.claude-plugin/plugin.json`. You can also pass a folder that keeps a `.claude-plugin/marketplace.json` beside its plugin folders. As long as that `.claude-plugin/` directory holds no `plugin.json`, the plugin folders still load. Nothing is installed or enabled from the marketplace file, because Claude Code doesn’t read it. Loading plugins from such a folder requires Claude Code v2.1.281 or later. In an interactive session, you can also add and remove plugins in the folder after startup: @@ -194,7 +194,7 @@ ​ -From a URL +Load a plugin from a URL When you start `claude` from your shell, pass `--plugin-url` with the address of a `.zip` archive, such as a build artifact your CI publishes: @@ -206,7 +206,7 @@ ​ -From an environment variable +Load plugins from an environment variable To load plugins in a session where you can’t add the `--plugin-dir` flag, list their absolute paths in the [`CLAUDE_CODE_PLUGIN_DIRS`](</docs/en/env-vars#variables>) environment variable instead. Claude Code loads each path as it loads a `--plugin-dir` path. These plugins load in addition to any you pass with `--plugin-dir`. [Project and local settings can’t set this variable](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). `CLAUDE_CODE_PLUGIN_DIRS` requires Claude Code v2.1.280 or later. Managed settings can turn off `--plugin-dir` and `CLAUDE_CODE_PLUGIN_DIRS`. See [Flags that load a plugin for one session](</docs/en/plugins/cli-reference#flags-that-load-a-plugin-for-one-session>). To test a plugin together with a plugin it depends on, see [Test a plugin and its dependency locally](</docs/en/plugins/dependencies#test-a-plugin-and-its-dependency-locally>).
modified Environment variables View current →
--- a/env-vars.md +++ b/env-vars.md @@ -17,7 +17,7 @@ ​ -In your shell +Set variables in your shell Set the variable before launching `claude`: @@ -60,7 +60,7 @@ ​ -In settings files +Set variables in settings files Add variables under the `env` key in a `settings.json` file, creating the file if it doesn’t exist. Claude Code reads them directly from the file, so they take effect no matter how `claude` was launched. A running session applies new and changed values to its environment when you save the file, but a feature that reads its variables once at startup, such as [OpenTelemetry monitoring](</docs/en/monitoring-usage>), keeps its startup values until you relaunch. Removing a variable from the file doesn’t unset it in a running session; the removal takes effect the next time you launch `claude`. @@ -90,7 +90,7 @@ Precedence -Some behaviors have both an environment variable and a dedicated settings key, and which one Claude Code reads first differs per key. For `ANTHROPIC_MODEL` and `CLAUDE_CODE_AUTO_CONNECT_IDE`, Claude Code reads the variable first and uses the `model` or `autoConnectIde` setting only when the variable is unset. For the pair you’re setting, check the variable’s row below and the key’s entry on the [settings reference](</docs/en/settings-reference>). When the same variable is set in both your shell and a settings file `env` block, the settings file value applies in most sessions. Claude Code writes each `env` entry into the process environment, replacing the value inherited from the shell. [How `env` values interact with your shell](</docs/en/settings-reference#how-env-values-interact-with-your-shell>) covers the sessions that keep the inherited value instead, and the [`env` setting](</docs/en/settings-reference#when-claude-code-applies-env-values>) says when it applies them. A few variables are special-cased; the [`env` setting](</docs/en/settings-reference#env>) lists the exceptions. In a settings file you can set a variable but you can’t remove one. To override a variable you can’t unset, such as a stale `CLAUDE_CODE_USE_VERTEX` exported by a shell profile you don’t control, set it to an empty string in the `env` block: `"CLAUDE_CODE_USE_VERTEX": ""`. Claude Code treats the empty value as unset for provider selection. Subprocesses still inherit the empty value. Between settings files, `env` values follow [settings precedence](</docs/en/settings#settings-precedence>), so a managed settings entry overrides the same variable in user or project settings. Project and local settings can’t set some variables, such as `CLAUDE_CONFIG_DIR` and the OpenTelemetry exporter variables. [Variables Claude Code ignores in `env`](</docs/en/settings-reference#variables-claude-code-ignores-in-env>) lists them, along with the OpenTelemetry off values that still apply. How an environment variable interacts with CLI flags and in-session commands varies per feature: `--model` and `/model` override `ANTHROPIC_MODEL`, while `CLAUDE_CODE_EFFORT_LEVEL` overrides `--effort` and `/effort`. When a variable interacts with another configuration source, its row in the Variables list states the precedence or links to the page that documents it. Claude Code reads shell environment variables at startup, so changes to them take effect the next time you launch `claude`. Variables set under the `env` key in settings files are reapplied to a running session when the file changes, with the startup-only exception described in In settings files. +Some behaviors have both an environment variable and a dedicated settings key, and which one Claude Code reads first differs per key. For `ANTHROPIC_MODEL` and `CLAUDE_CODE_AUTO_CONNECT_IDE`, Claude Code reads the variable first and uses the `model` or `autoConnectIde` setting only when the variable is unset. For the pair you’re setting, check the variable’s row below and the key’s entry on the [settings reference](</docs/en/settings-reference>). When the same variable is set in both your shell and a settings file `env` block, the settings file value applies in most sessions. Claude Code writes each `env` entry into the process environment, replacing the value inherited from the shell. [How `env` values interact with your shell](</docs/en/settings-reference#how-env-values-interact-with-your-shell>) covers the sessions that keep the inherited value instead, and the [`env` setting](</docs/en/settings-reference#when-claude-code-applies-env-values>) says when it applies them. A few variables are special-cased; the [`env` setting](</docs/en/settings-reference#env>) lists the exceptions. In a settings file you can set a variable but you can’t remove one. To override a variable you can’t unset, such as a stale `CLAUDE_CODE_USE_VERTEX` exported by a shell profile you don’t control, set it to an empty string in the `env` block: `"CLAUDE_CODE_USE_VERTEX": ""`. Claude Code treats the empty value as unset for provider selection. Subprocesses still inherit the empty value. Between settings files, `env` values follow [settings precedence](</docs/en/settings#settings-precedence>), so a managed settings entry overrides the same variable in user or project settings. Project and local settings can’t set some variables, such as `CLAUDE_CONFIG_DIR` and the OpenTelemetry exporter variables. [Variables Claude Code ignores in `env`](</docs/en/settings-reference#variables-claude-code-ignores-in-env>) lists them, along with the OpenTelemetry off values that still apply. How an environment variable interacts with CLI flags and in-session commands varies per feature: `--model` and `/model` override `ANTHROPIC_MODEL`, while `CLAUDE_CODE_EFFORT_LEVEL` overrides `--effort` and `/effort`. When a variable interacts with another configuration source, its row in the Variables list states the precedence or links to the page that documents it. Claude Code reads shell environment variables at startup, so changes to them take effect the next time you launch `claude`. Variables set under the `env` key in settings files are reapplied to a running session when the file changes, with the startup-only exception described in Set variables in settings files. ## @@ -261,6 +261,7 @@ `CLAUDE_CODE_ENABLE_AUTO_MODE`| Accepted for compatibility with older releases and has no effect. Auto mode is available by default on every provider, including Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions. In v2.1.158 through v2.1.206, setting this to `1` was required to make [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) available on those providers `CLAUDE_CODE_ENABLE_AWAY_SUMMARY`| Override [session recap](</docs/en/interactive-mode#session-recap>) availability. Set to `0` to force recaps off regardless of the `/config` toggle. Set to `1` to force recaps on when [`awaySummaryEnabled`](</docs/en/settings-reference#awaysummaryenabled>) is `false`. Takes precedence over the setting and `/config` toggle `CLAUDE_CODE_ENABLE_BACKGROUND_PLUGIN_REFRESH`| Set to `1` to refresh plugin state at turn boundaries in [non-interactive mode](</docs/en/headless>) after a background install completes. Off by default because the refresh changes the system prompt mid-session, which invalidates [prompt caching](</docs/en/prompt-caching>) for that turn +`CLAUDE_CODE_ENABLE_CFC`| Set to `1` to start a CLI session with [Chrome integration](</docs/en/chrome>) on, or `0` to start with it off. Takes precedence over the [`claudeInChromeDefaultEnabled`](</docs/en/settings-reference#claudeinchromedefaultenabled>) setting. The `--chrome` and `--no-chrome` flags take precedence over both. Claude Code [ignores `1` in project and local settings](</docs/en/chrome#project-settings-can%E2%80%99t-turn-on-chrome>) `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL`| Set to `1` to route the “How is Claude doing?” session quality survey to your own [OpenTelemetry collector](</docs/en/monitoring-usage>) when Anthropic-bound nonessential traffic is blocked. Survey ratings are emitted only as OTEL events to your configured collector. No survey data is sent to Anthropic in this mode. Applies when `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_TELEMETRY`, or `DO_NOT_TRACK` is set, and has no effect otherwise. `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` and the organization product feedback policy take precedence `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING`| Controls whether tool call inputs stream from the API as Claude generates them. With this off, a large tool input such as a long file write arrives only after Claude finishes generating it, which can look like it’s hanging. Enabled by default on the Anthropic API. On Amazon Bedrock and Google Cloud’s Agent Platform, enabled per model where the deployed container supports it. Set to `0` to opt out. Set to `1` to force on when routing through a proxy via `ANTHROPIC_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL`, or `ANTHROPIC_BEDROCK_BASE_URL`. Off by default on Microsoft Foundry and [gateway](</docs/en/llm-gateway>) connections `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY`| Set to `1` to populate the `/model` picker from your gateway’s `/v1/models` endpoint when `ANTHROPIC_BASE_URL` points at an Anthropic-compatible gateway such as LiteLLM, Kong, or an internal proxy. Off by default because gateways backed by a shared API key would otherwise show every user every model the key can access. Discovered models are still filtered by an [`availableModels`](</docs/en/settings-reference#availablemodels>) allowlist the session receives; deliver the list through [MDM or a managed settings file](</docs/en/managed-settings#delivery-mechanisms>), since [server-managed delivery is not available on gateway configurations](</docs/en/server-managed-settings#platform-availability>) @@ -303,7 +304,7 @@ `CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION`| Cap on [WebSearch](</docs/en/tools-reference#session-search-limit>) calls (default: 200). When Claude reaches the cap, further WebSearch calls return a notice telling it to continue with the information it already gathered. Accepts a positive whole number with no upper bound. Anything else is ignored and the default applies, so the cap can be raised but not turned off. Requires Claude Code v2.1.212 or later `CLAUDE_CODE_MCP_ALLOWLIST_ENV`| Set to `1` to spawn stdio MCP servers with only a safe baseline environment plus the server’s configured `env`, instead of inheriting your shell environment `CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS`| Elapsed time in milliseconds before a still-running MCP tool call [moves to a background task](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>) (default: 120000, or 2 minutes). Set to `0` to turn automatic backgrounding off. Requires Claude Code v2.1.212 or later -`CLAUDE_CODE_MCP_STARTUP_WAIT_MS`| How long in milliseconds the first turn of a [non-interactive](</docs/en/headless>) session waits for MCP servers that are still connecting, in place of the default [first-turn wait](</docs/en/agent-sdk/mcp#connection-timing>). When set, the wait covers every pending server. Set to `0` to skip the wait. A [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) server keeps its own `MCP_TIMEOUT` wait regardless of the value. Requires Claude Code v2.1.274 or later +`CLAUDE_CODE_MCP_STARTUP_WAIT_MS`| How long in milliseconds the first turn of a [non-interactive](</docs/en/headless>) session waits for MCP servers that are still connecting, in place of the default [first-turn wait](</docs/en/agent-sdk/mcp#connection-timing>). When set, the wait covers every pending server; in a [self-hosted environment](</docs/en/self-hosted-environments-configuration#connection-timing>), it changes only how long the wait lasts. Set to `0` to skip the wait. A [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) server keeps its own `MCP_TIMEOUT` wait regardless of the value. Requires Claude Code v2.1.274 or later `CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`| Idle timeout in milliseconds for MCP tool calls. When a stdio, HTTP, SSE, WebSocket, or [claude.ai connector](</docs/en/mcp#use-mcp-servers-from-claude-ai>) MCP server sends no response and no progress notification for this long, the tool call aborts with an error instead of waiting for the overall `MCP_TOOL_TIMEOUT`. Overrides the per-transport defaults of 300000 (5 minutes) for network servers and 1800000 (30 minutes) for stdio servers. Set to `0` to disable the idle check. Values below 1000 are raised to one second, and the value is capped at the effective `MCP_TOOL_TIMEOUT`. A per-server `timeout` in `.mcp.json` of at least 1000 raises that server’s idle window to at least the `timeout` value. Doesn’t apply to IDE servers or SDK in-process servers. Requires Claude Code v2.1.187 or later. Before v2.1.203, stdio servers were exempt from the idle timeout `CLAUDE_CODE_MESSAGING_SOCKET`| Set by Claude Code, not by you: in sessions that bind an [inbox socket](</docs/en/cross-session-messaging#the-sessions-inbox-socket>), Claude Code exports that socket’s path to hooks and Bash commands when it binds the socket. In a session that starts with messaging on, Claude Code binds the socket before any hook runs. Other sessions on the machine deliver messages to this path. Each session exports its own socket rather than one inherited from a parent, and messages arriving on it go through the session’s [inbound controls](</docs/en/cross-session-messaging#control-inbound-messages>). Settings `env` blocks can’t set it. Requires Claude Code v2.1.224 or later `CLAUDE_CODE_MESSAGING_TOKEN`| Set by Claude Code, not by you: in sessions that bind an [inbox socket](</docs/en/cross-session-messaging#the-sessions-inbox-socket>), Claude Code exports this per-session token to hooks and Bash commands alongside `CLAUDE_CODE_MESSAGING_SOCKET`. A script posting to the socket can send `{"type":"auth","token":"<token>"}` as its first line to prove it belongs to the session. On native Windows, Claude Code requires this line and closes any connection that doesn’t open with a valid one. The [own-child rules](</docs/en/cross-session-messaging#the-sessions-inbox-socket>) say when Claude Code consults the token. Each session exports its own token, never one inherited from a parent session. Settings `env` blocks can’t set it. Requires Claude Code v2.1.228 or later
modified Error reference View current →
Show diff (183 lines)
--- a/errors.md +++ b/errors.md @@ -179,9 +179,9 @@ `<model> has safety measures that flagged this message for a cybersecurity topic`| Request errors `Details: `[reasoning_extraction]``| Request errors `API Error: Output blocked by content filtering policy`| Request errors -`Installation was killed before it could finish (exit code 137)`| Installation errors -`The connection dropped while downloading the update`| Installation errors -`Download timed out: exceeded the total deadline`| Installation errors +`Installation was killed before it could finish (exit code 137)`| [Troubleshoot installation and login](</docs/en/troubleshoot-install#installation-was-killed-before-it-could-finish>) +`The connection dropped while downloading the update`| [Troubleshoot installation and login](</docs/en/troubleshoot-install#the-connection-dropped-while-downloading-the-update>) +`Download timed out: exceeded the total deadline`| [Troubleshoot installation and login](</docs/en/troubleshoot-install#the-connection-dropped-while-downloading-the-update>) `--bg and --print conflict`| Command-line errors `Error: Cannot use both --append-subagent-system-prompt and --append-subagent-system-prompt-file. Please use only one.`| Command-line errors `Cloud sessions cannot be created from a --restricted session`| Command-line errors @@ -237,6 +237,7 @@ `Windows reported an error (EBADF) when Claude Code read this session's transcript file`| Command-line errors `Cannot switch renderers in this session`| Command-line errors `Cannot switch renderers while work is running in the background`| Command-line errors +`Claude Code couldn't restart`| Command-line errors `Couldn't open Claude Desktop`| Command-line errors `Failed to open Claude Desktop. Please try opening it manually.`| Command-line errors `Couldn't read your Zed keymap` / `Couldn't back up your Zed keymap` / `Couldn't update your Zed keymap`| Command-line errors @@ -251,6 +252,7 @@ `Marketplace name impersonates an official Anthropic/Claude marketplace`| Plugin errors `Marketplace "<name>" is already added from a different source`| Plugin errors `"<name>" is another spelling of "<reserved>", a reserved marketplace name`| Plugin errors +`Cannot add marketplace "<name>": Claude Code cannot install plugins from a marketplace with this name`| [Plugin troubleshooting](</docs/en/plugins/troubleshooting#cannot-install-plugins-from-a-marketplace-with-this-name>) `Marketplace "<name>" is added but ignored`| [Plugin troubleshooting](</docs/en/plugins/troubleshooting#marketplace-is-added-but-ignored>) `Marketplace "<name>" is registered but was refused (see the debug log)`| [Plugin troubleshooting](</docs/en/plugins/troubleshooting#marketplace-is-added-but-ignored>) `references ${user_config.*} in a shell-form command`| Plugin errors @@ -259,6 +261,7 @@ `Plugin archive integrity check failed`| Plugin errors `An npm plugin source must name a registry package`| [Plugin troubleshooting](</docs/en/plugins/troubleshooting#an-npm-plugin-source-must-name-a-registry-package>) `The packages it lists are not installed` / `The packages it lists were not installed, because`| [Plugin troubleshooting](</docs/en/plugins/troubleshooting#the-packages-it-lists-are-not-installed>) +`does not load (...), so Claude Code ignores the whole file`| [Plugin troubleshooting](</docs/en/plugins/troubleshooting#does-not-load-so-claude-code-ignores-the-whole-file>) `path escapes plugin directory`| Plugin errors `path could not be checked`| Plugin errors `its marketplace entry path does not stay inside the marketplace directory`| Plugin errors @@ -269,6 +272,7 @@ `"<plugin>" was not uninstalled: it is still switched on in <file>`| Plugin errors `"<plugin>" was not uninstalled: <file> is there and could not be read`| Plugin errors `Plugin "<plugin>" was not uninstalled: installed_plugins.json`| [Plugin troubleshooting](</docs/en/plugins/troubleshooting#installed-plugins-json-holds-a-record-this-version-cannot-read>) +`Plugin directory does not exist: <path>`| [Plugin troubleshooting](</docs/en/plugins/troubleshooting#plugin-directory-does-not-exist>) `Error: No such tool available: <tool name>`| Tool errors `would be spawned with zero tools — refusing`| Tool errors `File is covered by a Read deny rule in your permission settings`| Tool errors @@ -321,6 +325,7 @@ `Session isn't responding` / `Press enter again to restart this session — it isn't responding`| Background session errors `Session <id> was stopped while the respawn was in flight`| Background session errors `This session was running agent '<name>', which is no longer available`| Background session errors +`This session restarted <time> after its next /loop wakeup was due, so that wakeup will not fire`| Background session errors `CLAUDE_CODE_PROCESS_WRAPPER: launcher ...`| Background session errors `EUNKNOWN: unknown error, uv_spawn`| Background session errors `EACCES: permission denied, posix_spawn`| Background session errors @@ -422,6 +427,7 @@ ---|---|--- [`CLAUDE_CODE_MAX_RETRIES`](</docs/en/env-vars>)| 10| Number of retry attempts. Capped at 15 as of v2.1.186; as of v2.1.199 `CLAUDE_CODE_RETRY_WATCHDOG` raises the default and removes the cap. Lower it to surface failures faster in scripts. [`CLAUDE_CODE_RETRY_WATCHDOG`](</docs/en/env-vars>)| unset| Set to `1` in unattended sessions such as CI jobs to retry `429` and `529` capacity errors indefinitely instead of failing after `CLAUDE_CODE_MAX_RETRIES` attempts. Claude Code fails at once when a standard-speed request gets a `429` that reports a spend limit or exhausted usage credits, even one from a gateway spend cap that resets on a schedule. Before v2.1.239, the watchdog retried these indefinitely. For fast mode requests, see [Handle rate limits](</docs/en/fast-mode#handle-rate-limits>). On v2.1.199 or later it also raises the default retry count for other transient errors, such as server errors, timeouts, and dropped connections, to 300, roughly three hours of backoff, and removes the cap of 15 on `CLAUDE_CODE_MAX_RETRIES` if you set that variable explicitly. +[`CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS`](</docs/en/env-vars>)| unset| Maximum time in milliseconds that each API request spends waiting out `429` and `529` errors when `CLAUDE_CODE_RETRY_WATCHDOG` is set. When unset, the wait has no limit. Requires Claude Code v2.1.295 or later. [`CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS`](</docs/en/env-vars>)| 500| Starting delay in milliseconds of the backoff between retries of a request that the API rejects with a `529` overloaded error. Raise it, up to 32000, to spread the retries over a longer window when the API is at capacity. Has no effect when `CLAUDE_CODE_RETRY_WATCHDOG` is set to `1`, or when the rejected request was sent in [fast mode](</docs/en/fast-mode#handle-rate-limits>). Requires Claude Code v2.1.292 or later. [`API_TIMEOUT_MS`](</docs/en/env-vars>)| 600000| Per-request timeout in milliseconds. Raise it for slow networks or proxies. It also caps how long Claude Code waits for response headers, described in No response from API. [`CLAUDE_CODE_NONSTREAMING_TIMEOUT_RETRIES`](</docs/en/env-vars>)| unset| Limit on re-sends of a non-streaming request that times out. At the limit, the request fails. A response from Claude that takes longer than the timeout to generate times out again on every re-send, so set a low number such as `0` to fail sooner. Each non-streaming attempt times out after 300 seconds in a local session, or after `API_TIMEOUT_MS` when you set a positive value. Requires Claude Code v2.1.285 or later. @@ -2517,47 +2523,6 @@ ​ -Installation errors - -These errors appear while installing or updating Claude Code, from the [install script](</docs/en/setup#install-claude-code>), `claude install`, or `claude update`. For `command not found`, PATH, permission, and TLS problems during setup, see [Troubleshoot installation and login](</docs/en/troubleshoot-install>). - -### - -​ - -Installation was killed before it could finish - -The install script reports when the `claude install` step is terminated by a signal. On Linux, exit code 137 means the process received SIGKILL, and on a low-memory host that’s usually the kernel out-of-memory (OOM) killer. The script prints this explanation and exits with code 137: - - Installation was killed before it could finish (exit code 137). This usually means the system ran out of memory. - Claude Code needs roughly 512MB of free memory to install. Free up memory, then run this script again. - -For any other fatal signal, and for exit code 137 on macOS, the script prints `Installation was killed before it could finish (exit code <N>)` with the actual exit code and omits the out-of-memory explanation. The message comes from the install script macOS and Linux use, which also covers installs inside WSL; the native Windows install scripts never print it. Before v2.1.200, the script exited with only the shell’s bare `Killed` line. **What to do:** - - * Stop other processes to free memory, then rerun the installer - * Add swap space or move to a larger instance. See [Install killed on low-memory Linux servers](</docs/en/troubleshoot-install#install-killed-on-low-memory-linux-servers>) for the swap-file commands. - -### - -​ - -The connection dropped while downloading the update - -The connection to the download server closed while `claude install` or `claude update` was fetching the Claude Code binary, and the retries didn’t recover. Claude Code retries the download when the connection drops, the transfer stalls, or the downloaded file fails its checksum, up to three attempts in total. A completed HTTP error, such as a 404, isn’t retried because the server already answered. Before v2.1.202, a single dropped connection failed the download immediately with the bare error `aborted` instead of retrying. - - The connection dropped while downloading the update (attempt 3/3: aborted). Check your network — proxies sometimes cut off large downloads. - -The text in parentheses names which attempt failed and the underlying network error. `claude update` precedes the message with `Error: Failed to install native update` on stderr. A download that stays connected but doesn’t finish within 10 minutes fails with `Download timed out: exceeded the total deadline` instead. Claude Code doesn’t retry a timed-out download, because a connection too slow to finish inside the deadline won’t finish on an immediate retry either. The steps below apply to both messages. A proxy or gateway can close a long transfer before it finishes, and the Claude Code binary is a large download. **What to do:** - - * Run `claude update` again. On an otherwise healthy network, the download usually succeeds on the next run. For the timed-out message, run it again from a faster or less throttled network. - * If your network requires a proxy, set `HTTPS_PROXY` before running the installer or `claude update`. See [Check network connectivity](</docs/en/troubleshoot-install#check-network-connectivity>). - * If a corporate proxy keeps closing the transfer, ask your network team to allow the full download from `downloads.claude.ai`. See [Network access requirements](</docs/en/network-config#network-access-requirements>). - * Run `claude doctor` from your shell for installation diagnostics - -## - -​ - Command-line errors These errors come from the `claude` command line and its subcommands, from a command name you submit at the prompt, and from commands such as `/security-review` that gather context by running shell commands before their prompt runs. They also come from `/tui`, which relaunches the CLI. @@ -3362,6 +3327,21 @@ **What to do:** * In a session started without those restrictions, run `/tui fullscreen`, or `/tui default` to switch back. Claude Code saves the [`tui` setting](</docs/en/settings-reference#tui>) there + +### + +​ + +Claude Code couldn’t restart + +Claude Code was restarting, for example to switch to or from fullscreen rendering after you ran [`/tui`](</docs/en/fullscreen#enable-fullscreen-rendering>). It closed the session but couldn’t start the new process, so it printed this message and exited with status 1: + + Claude Code couldn't restart. Your conversation is saved. Start Claude Code again and run /resume to pick it up. + +When the restart had no conversation to reopen, for example because `/tui` was your first input in a new session, the message reads `Claude Code couldn't restart. Start Claude Code again.` **What to do:** + + * Run `claude` again in your shell from the same directory. If the message said your conversation is saved, run [`/resume`](</docs/en/sessions#resume-a-session>) in the new session and select it + * If restarts keep failing, start Claude Code from your shell with [`claude --debug-file claude-debug.log`](</docs/en/cli-reference#cli-flags>). If a restart from that session fails, `claude-debug.log` in the directory you started from records a `Failed to relaunch:` line with the operating system’s error. Include that line when you report the problem ### @@ -4206,19 +4186,19 @@ Command blocked by the worktree isolation checks -Claude ran a Bash or Monitor command in a [session isolated in a worktree](</docs/en/worktrees#how-claude-code-enforces-isolation>), and Claude Code refused it for one of two reasons: - - * The command points git at the main checkout. - * Claude Code can’t verify from the command text that any git the command runs stays inside the worktree. A command that never names git can still be refused for this reason, because expanding a variable indirection such as `${!name}` or running a Bash function substitution such as `${ command; }` produces a value at runtime that can itself be a command. - -The middle of the message names what couldn’t be verified: +Claude ran a Bash, [PowerShell](</docs/en/tools-reference#powershell-tool>), or [Monitor](</docs/en/tools-reference#monitor-tool>) command in a [session isolated in a worktree](</docs/en/worktrees#how-claude-code-enforces-isolation>), and Claude Code refused it for one of these reasons: + + * The command would run in the main checkout or in another worktree. The message says its working directory `resolved to the shared checkout` or `is in a different worktree`. + * A Bash or Monitor command points git at the main checkout. + * Claude Code can’t verify from a Bash or Monitor command’s text that any git the command runs stays inside the worktree. A command that never names git can still be refused for this reason, because expanding a variable indirection such as `${!name}` or running a Bash function substitution such as `${ command; }` produces a value at runtime that can itself be a command. + +The message says `is isolated in the worktree <path>, but this command`, followed by the reason, such as a command whose text Claude Code couldn’t verify: This session is isolated in the worktree /path/to/worktree, but this command evaluates ${!x@P} arithmetically inside a construct too complex to verify, which can run a command hidden in a variable's value. Refusing to run it — a worktree-isolated session's git operations must target its own worktree. Split it into plain, separate commands and run them from /path/to/worktree. **What to do:** - * Usually nothing: Claude reads the message and rewrites the command the way its final sentence asks - * If a command you asked for keeps being refused, spell the flagged value literally: replace the indirection or substitution with its value, and run git as its own plain command from inside the worktree + * **Git pointed at the main checkout, or command text that can’t be verified** : nothing. Claude reads the message and rewrites the command the way its final sentence asks. If a command you asked for keeps being refused over an expansion in its text, spell the flagged value literally and run git as its own plain command from inside the worktree * To act on the main checkout on purpose, run the command yourself in a terminal outside the session ### @@ -4365,6 +4345,21 @@ * Re-create the agent file at `.claude/agents/<name>.md` in the session’s project, or at `~/.claude/agents/<name>.md` for a personal agent, then resume again * Or resume with `--agent <name>` naming an agent that does exist, to run the session as that agent instead * If the agent is project-scoped and you haven’t trusted the session’s original directory, run Claude Code there once, accept the trust dialog, then resume again + +### + +​ + +This session restarted after its next /loop wakeup was due + +A [self-paced `/loop`](</docs/en/scheduled-tasks#let-claude-choose-the-interval>) in a [background session](</docs/en/agent-view>) has stopped. The session’s process ended while the loop was waiting for its next wakeup, and that wakeup came due before the session’s [next process](</docs/en/agent-view#the-supervisor-process>) started. The missed wakeup doesn’t fire late. The notice says how overdue the wakeup was when the session restarted: + + This session restarted 12m after its next /loop wakeup was due, so that wakeup will not fire. The loop stays stopped until Claude schedules it again: reply to continue it. + +Before v2.1.295, the loop stopped in this situation without a notice. **What to do:** + + * To continue the loop, [reply to the session](</docs/en/agent-view#peek-and-reply>) and say so, such as `keep the loop running`. Claude reads the notice with your reply and can schedule the next wakeup + * If you’re done with the loop, do nothing. It has already stopped ###
modified React to events with a mod View current →
--- a/events.md +++ b/events.md @@ -121,7 +121,14 @@ return result }) -After Claude edits or writes an `.mdx` file, a dim line in the transcript names the file. Nothing is logged for another kind of file, or for a call that was refused or failed. Claude’s view of the call doesn’t change, because the hook returns the result it received. To change a call, pass changed arguments to `next`. To retry a call, call `next(e)` again: a hook that sees `isError` on the first result can run the tool a second time and return that result. To answer a call yourself, return an object with a `result` field, such as `{ result: 'Skipped by my-mod' }`, without calling `next`. When you do that, no permission prompt appears and the tool doesn’t run, so the result you return is all Claude learns about what happened. Hooks in your organization’s [managed settings](</docs/en/server-managed-settings>) run before any mod’s `tool.call` hook, and a block from one of them is final. +After Claude edits or writes an `.mdx` file, a dim line in the transcript names the file. Nothing is logged for another kind of file, or for a call that was refused or failed. Claude’s view of the call doesn’t change, because the hook returns the result it received. Your hook can also change a call, retry it, answer it itself, or withhold its result: + + * **Change the call** : pass changed arguments to `next`. + * **Retry the call** : call `next(e)` again. A hook that sees `isError` on the first result can run the tool a second time and return that result. + * **Answer the call yourself** : return an object with a `result` field, without calling `next`, and for a built-in tool, give `result` the shape that tool’s own result has in [the types for your build](</docs/en/plugins/mods/create#get-the-types-for-your-build>). No permission prompt appears and the tool doesn’t run, so the result you return is all Claude learns about what happened. + * **Withhold the result from Claude** : return `{ deny: reason }` after `await next(e)`. Claude reads your reason in place of what `next` returned. When the tool ran, the deny keeps its result from Claude and undoes nothing the tool did. When the tool ran and succeeded, the reason follows a note such as `Bash ran, and a plugin withheld its result:`. + +Hooks in your organization’s [managed settings](</docs/en/server-managed-settings>) run before any mod’s `tool.call` hook, and a block from one of them is final. #### @@ -191,7 +198,7 @@ To do this| Return this ---|--- -Rewrite the prompt. The message in the transcript shows the new text.| `next({ ...e, text: newText })` +Rewrite the prompt. The transcript and your [prompt history](</docs/en/interactive-mode#command-history>) show the new text.| `next({ ...e, text: newText })` Add text only Claude reads, after the prompt| `next({ ...e, context: [...(e.context ?? []), extraText] })` Stop the prompt from being sent| `{ drop: 'the reason' }` @@ -207,7 +214,7 @@ return next({ ...e, context: [...(e.context ?? []), 'Current branch: ' + git.stdout.trim()] }) }) -When you send a prompt such as `open a PR for this change`, your message looks the same in the transcript, and Claude also reads a line such as `Current branch: feature/auth` after it. A prompt that doesn’t mention a pull request goes through unchanged, and `git` doesn’t run. To stop a prompt, return `{ drop: 'the reason' }` without calling `next`. If your hook returns a `drop` after its `next(e)` call let the prompt through, the turn still runs, and the hook fails with a message that includes `a drop after its next() was answered`. [Other events](</docs/en/plugins/mods/reference#prompts-and-what-claude-reads>) cover the rest of what Claude reads: `prompt.section` for each section of the system prompt, `prompt.context` for the context sent with the first message, and `skill.prompt` for a skill’s text. Text from these hooks that changes between requests [invalidates the prompt cache](</docs/en/prompt-caching>). +When you send a prompt such as `open a PR for this change`, your message looks the same in the transcript, and Claude also reads a line such as `Current branch: feature/auth` after it. A prompt that doesn’t mention a pull request goes through unchanged, and `git` doesn’t run. To stop a prompt, return `{ drop: 'the reason' }` without calling `next`. The text goes back into the user’s prompt input, and they see `Prompt dropped by a hook:` followed by your reason, so address the reason to them. If your hook returns a `drop` after its `next(e)` call let the prompt through, the turn still runs, and the hook fails with a message that includes `a drop after its next() was answered`. [Other events](</docs/en/plugins/mods/reference#prompts-and-what-claude-reads>) cover the rest of what Claude reads: `prompt.section` for each section of the system prompt, `prompt.context` for the context sent with the first message, and `skill.prompt` for a skill’s text. Text from these hooks that changes between requests [invalidates the prompt cache](</docs/en/prompt-caching>). ### @@ -323,6 +330,8 @@ * **`tool.check`** : return `{ decision: 'deny', reason: 'the reason' }` * **`plugin.register`** : return `{ refuse: 'the reason' }`, as [Refuse mods when your check fails](</docs/en/plugins/mods/admin#refuse-mods-when-your-check-fails>) shows +At `tool.call`, a `deny` returned after `next` resolved withholds the result from Claude. + ## ​
modified Glossary View current →
--- a/glossary.md +++ b/glossary.md @@ -473,7 +473,7 @@ Teleport -A command, `/teleport`, that pulls a cloud Claude Code session into your local terminal. Claude fetches the branch, loads the conversation history, and resumes from the cloud session’s last state. The reverse direction is `--cloud`, which sends a local task to run in the cloud. Learn more: [From cloud to terminal](</docs/en/claude-code-on-the-web#from-cloud-to-terminal>) +A command, `/teleport`, that pulls a cloud Claude Code session into your local terminal. Claude fetches the branch, loads the conversation history, and resumes from the cloud session’s last state. The reverse direction is `--cloud`, which sends a local task to run in the cloud. Learn more: [Continue a cloud session in your terminal](</docs/en/claude-code-on-the-web#from-cloud-to-terminal>) ###
modified Run Claude Code programmatically View current →
--- a/headless.md +++ b/headless.md @@ -65,7 +65,7 @@ * **[Monitor](</docs/en/tools-reference#monitor-tool>) watches**: the run waits until the watch times out or the 10-minute cap ends the wait, whichever comes first. While it waits, Claude keeps responding to what the watch reports. By default, a watch times out five minutes after Claude starts it. * **Pending wakeups** : in a run whose prompt you passed as text rather than with `--input-format stream-json`, when Claude has scheduled a [self-paced `/loop` wakeup](</docs/en/scheduled-tasks#let-claude-choose-the-interval>), the run waits for each wakeup to fire and runs its iteration until the [loop ends](</docs/en/scheduled-tasks#stop-a-loop>), even past the 10-minute cap. -If the run reaches its [`--max-budget-usd`](</docs/en/cli-reference#cli-flags>) cap, Claude Code stops the remaining background work instead of waiting. When background work starts another turn, the run prints each turn’s result with the default `text` output and the last turn’s result with `json` output. Before v2.1.295, the run printed only the last turn’s result with `text` output too. +When stderr is a terminal and the run has waited five seconds, Claude Code prints a line to stderr that starts with `Waiting for background work to finish` and names the work. With `json` or `stream-json` output, the line prints only when stdout isn’t a terminal, so the JSON your script reads never carries it. If the run reaches its [`--max-budget-usd`](</docs/en/cli-reference#cli-flags>) cap, Claude Code stops the remaining background work instead of waiting. When background work starts another turn, the run prints each turn’s result with the default `text` output and the last turn’s result with `json` output. Before v2.1.295, the run printed only the last turn’s result with `text` output too. ### @@ -254,7 +254,7 @@ `plugins`| array| plugins that loaded successfully, each with `name` and `path` `plugin_errors`| array| plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. A plugin that didn’t load is absent from `plugins`. The key is omitted when there are no errors -When a `--plugin-dir` directory or archive itself fails to load, its `plugin_errors` entry includes the resolved absolute path as `path`. Use it to tell which of several `--plugin-dir` values failed. The `path` field requires Claude Code v2.1.283 or later. Use the MCP server fields the same way. When you pass [`--mcp-config`](</docs/en/cli-reference#cli-flags>) with `-p`, Claude Code waits for still-pending servers before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. A remote server with a [cached tool list](</docs/en/agent-sdk/mcp#connection-timing>) skips the wait, shows `pending` in `system/init`, and connects on its first tool call. The wait requires Claude Code v2.1.221 or later. Claude Code validates each `--mcp-config` entry at startup and skips entries that fail validation, for example a `url` entry with no `type`. The run continues and exits cleanly, so check these fields to catch a server that never loaded: +When a `--plugin-dir` directory or archive itself fails to load, its `plugin_errors` entry includes the resolved absolute path as `path`. Use it to tell which of several `--plugin-dir` values failed. The `path` field requires Claude Code v2.1.283 or later. Use the MCP server fields the same way. When you pass [`--mcp-config`](</docs/en/cli-reference#cli-flags>) with `-p`, Claude Code waits for still-pending servers before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. A remote server with a [cached tool list](</docs/en/agent-sdk/mcp#connection-timing>) skips the wait, shows `pending` in `system/init`, and connects on its first tool call. In a [self-hosted environment](</docs/en/self-hosted-environments-configuration#connection-timing>), a shorter wait applies instead. The wait requires Claude Code v2.1.221 or later. Claude Code validates each `--mcp-config` entry at startup and skips entries that fail validation, for example a `url` entry with no `type`. The run continues and exits cleanly, so check these fields to catch a server that never loaded: Field| Type| Description ---|---|---
modified Set up Claude Code (local mode) for a HIPAA-ready organization View current →
--- a/hipaa-setup.md +++ b/hipaa-setup.md @@ -121,6 +121,8 @@ "cleanupPeriodDays": 30 } +For a fuller `managed-settings.json` with sandboxing, a network allowlist, credential protections, and local data retention, see `settings-hipaa.json` and `README-hipaa.md` in the [settings examples repository](<https://github.com/anthropics/claude-code/tree/main/examples/settings>). + #### ​ @@ -302,6 +304,7 @@ * [Set up Cowork (local mode) for a HIPAA-ready organization](<https://claude.com/docs/cowork/hipaa-setup>) * [Deploy managed settings](</docs/en/managed-settings>) + * [HIPAA settings example](<https://github.com/anthropics/claude-code/tree/main/examples/settings>) * [Enterprise network configuration](</docs/en/network-config>) * [Zero data retention](</docs/en/zero-data-retention>) * [Legal and compliance](</docs/en/legal-and-compliance>)
modified Automate actions with hooks View current →
--- a/hooks-guide.md +++ b/hooks-guide.md @@ -198,7 +198,7 @@ } } -To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. When the hook succeeds, Claude Code shows nothing in the conversation. To confirm the hook ran, check that the edited file is reformatted, or see Debug techniques. To reformat a specific file however it changes, including when a `Bash` command rewrites it, use a [FileChanged](</docs/en/hooks#filechanged>) hook instead. +To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier’s default settings, the hook rewrites them to double quotes. When the hook succeeds, Claude Code shows nothing in the conversation. To confirm the hook ran, check that the edited file is reformatted, or see Check what a hook did. To reformat a specific file however it changes, including when a `Bash` command rewrites it, use a [FileChanged](</docs/en/hooks#filechanged>) hook instead. The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](<https://jqlang.org/download/>). @@ -859,7 +859,12 @@ } } -The endpoint should return a JSON response body using the same [output format](</docs/en/hooks#json-output>) as command hooks. To block a tool call, return a 2xx response with the appropriate `hookSpecificOutput` fields. HTTP status codes alone can’t block actions. Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference. +Your endpoint responds with a JSON body in the same [output format](</docs/en/hooks#json-output>) as command hooks, and Claude Code also checks the response status: + + * **2xx status** : to block a tool call, return the appropriate `hookSpecificOutput` fields in the body. + * **Any other status, or the request fails** : Claude Code reports a [non-blocking error](</docs/en/hooks#exit-code-output>) and lets the action continue. To make a failed endpoint block the action, set [`onFailure: "block"`](</docs/en/hooks#block-the-action-when-a-hook-fails>) on the hook. + +Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty. For full configuration options and response handling, see [HTTP hooks](</docs/en/hooks#http-hook-fields>) in the reference. ## @@ -983,16 +988,16 @@ ​ -Debug techniques - -Press `Ctrl+O` to open the transcript view to check the outcome of a hook run: - - * **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 - * **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 or parse 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. +Check what a hook did + +Press `Ctrl+O` to open the transcript view and look for the hook’s outcome: + + * **Success** : you see nothing, unless the hook’s JSON surfaces something, such as `systemMessage` or Stop hook feedback. + * To confirm the hook ran, check for its effect, like a reformatted file + * **Blocking error** : on most events you see the message that came with the block, for example `Blocked: rm commands are not allowed`. On a few events, such as `ConfigChange` and `Elicitation`, you see no message. [Exit code 2](</docs/en/hooks#exit-code-2>) covers where the message comes from. + * **Non-blocking error** : you see a `<hook name> hook error` notice with a short explanation, such as the first line of stderr after `Failed with non-blocking status code:`, or a JSON validation or parse message. The action went ahead. + +To look up the outcome for a specific exit code and stdout, including the per-event exceptions, see [Exit code output](</docs/en/hooks#exit-code-output>) in the reference. For full execution details including hook 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 Host and maintain a marketplace View current →
--- a/host-marketplace.md +++ b/host-marketplace.md @@ -397,7 +397,13 @@ How users accept a headersHelper command -A user accepts a plugin entry’s command each time they install or update that one plugin by itself. They do that from the plugin’s own view in `/plugin`, or with `claude plugin install` or `claude plugin update`. Claude Code shows the command and the archive URL, and runs the command only after the user accepts. In a non-interactive shell, pass [`--yes`](</docs/en/plugins/cli-reference#plugin-install>) to accept the command. To accept only the command that a previous `--json` run displayed, pass [`--accept-command`](</docs/en/plugins/cli-reference#plugin-install>) with the `sha256` the run reported. Claude Code runs only the command it showed, for the archive URL it showed. If the entry’s command or archive URL changed in between, Claude Code refuses the install or update. A change in the query string alone doesn’t count. +A user accepts a plugin entry’s command each time they install or update that one plugin by itself. Claude Code shows the command and the archive URL, and runs the command only after the user accepts. Users can install or update the plugin inside a Claude Code session in a terminal, in their shell with no session running, or in the VS Code extension: + + * **Terminal session** : from the plugin’s own view in `/plugin`. + * **Shell** : with `claude plugin install` or `claude plugin update`. + * **VS Code extension** : from the [**Manage plugins** dialog](</docs/en/vs-code#manage-plugins>), with version 2.1.290 or later of the extension. + +In a non-interactive shell, pass [`--yes`](</docs/en/plugins/cli-reference#plugin-install>) to accept the command. To accept only the command that a previous `--json` run displayed, pass [`--accept-command`](</docs/en/plugins/cli-reference#plugin-install>) with the `sha256` the run reported. Claude Code runs only the command it showed, for the archive URL it showed. If the entry’s command or archive URL changed in between, Claude Code refuses the install or update. A change in the query string alone doesn’t count, except in the VS Code extension or with `--accept-command`. ###
modified Install and manage plugins View current →
--- a/install.md +++ b/install.md @@ -240,7 +240,7 @@ claude plugin install deploy-helper --marketplace your-org/plugins -The shell command adds the marketplace without a confirmation step. A marketplace you’ve already added from that source is reused. A new one is added under the same [organization policy checks](</docs/en/plugins/org#restrict-what-users-can-install>) as `claude plugin marketplace add`, and is declared in your user settings even when you pass `--scope project`. +The shell command adds the marketplace without a confirmation step. A marketplace you’ve already added from that source is reused. A new one is added under the same [organization policy checks](</docs/en/plugins/org#restrict-what-users-can-install>) as `claude plugin marketplace add`, and is declared in your user settings even when you pass `--scope project`. If you haven’t added that marketplace yet, the command prints `Successfully added marketplace: <name> (declared in user settings)` and then installs the plugin. ###
modified Interactive mode View current →
--- a/interactive-mode.md +++ b/interactive-mode.md @@ -210,10 +210,10 @@ `^`| First non-blank character `gg`| Beginning of input `G`| Beginning of last line -`f{char}`| Jump to next occurrence of character -`F{char}`| Jump to previous occurrence of character -`t{char}`| Jump to just before next occurrence of character -`T{char}`| Jump to just after previous occurrence of character +`f{char}`| Jump to next occurrence of character on the current line +`F{char}`| Jump to previous occurrence of character on the current line +`t{char}`| Jump to just before next occurrence of character on the current line +`T{char}`| Jump to just after previous occurrence of character on the current line `;`| Repeat last f/F/t/T motion `,`| Repeat last f/F/t/T motion in reverse `/`| 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 @@ -233,7 +233,7 @@ `dd`| Delete line `D`| Delete to end of line `dw`/`de`/`db`| Delete word/to end/back -`df{char}`/`dt{char}`| Delete to and including, or up to, the next occurrence of a character +`df{char}`/`dt{char}`| Delete to and including, or up to, the next occurrence of a character on the current line `dj`/`dk`| Delete the current line and the line below or above `dgg`/`dG`| Delete from the current line to the first or last line `d0`/`c0`/`y0`| Delete, change, or yank from the cursor back to the beginning of the line. Requires Claude Code v2.1.281 or later @@ -810,6 +810,7 @@ * A bare `#123` * A nested GitLab path such as `group/subgroup/project#123` * Any reference inside a code span or code block + * Any reference in a reply longer than about 1,000 lines or 100,000 characters Claude Code builds the link for the host of the repository it identifies from your git remote, not for the repository the reference names:
modified JetBrains IDEs View current →
--- a/jetbrains.md +++ b/jetbrains.md @@ -59,7 +59,7 @@ ​ -From your IDE +Run Claude Code from your IDE Run `claude` from your IDE’s integrated terminal, and all integration features will be active. @@ -67,7 +67,7 @@ ​ -From external terminals +Connect from an external terminal Use the `/ide` command in any external terminal to connect Claude Code to your JetBrains IDE and activate all features:
modified Deploy managed settings View current →
--- a/managed-settings.md +++ b/managed-settings.md @@ -65,7 +65,7 @@ File-based| As `managed-settings.json` in a system directory on each machine; see where each mechanism stores the policy| Read at startup and reloaded when a file changes| Machines without MDM, Linux hosts, or images you build yourself HKCU registry, Windows and WSL| As a Windows `HKCU` registry value; see where each mechanism stores the policy| Read at startup and checked for changes every 30 minutes; Claude Code uses it only when no admin document is present above it and no host-supplied parent settings supply a restrictive key| You can’t write the machine-level `HKLM` key -Starter templates for Jamf, Iru, Intune, and Group Policy are in the [MDM examples repository](<https://github.com/anthropics/claude-code/tree/main/examples/mdm>). For managed MCP servers, which you deploy alongside any of these through `managed-mcp.json` or provide through the [`managedMcpServers`](</docs/en/settings-reference#managedmcpservers>) key, see [Managed MCP configuration](</docs/en/managed-mcp>). +Starter templates for Jamf, Iru, Intune, and Group Policy are in the [MDM examples repository](<https://github.com/anthropics/claude-code/tree/main/examples/mdm>). If your organization has the [HIPAA configuration](</docs/en/hipaa-setup#deploy-managed-settings>) applied, see `settings-hipaa.json` and `README-hipaa.md` in the [settings examples repository](<https://github.com/anthropics/claude-code/tree/main/examples/settings>) for a fuller `managed-settings.json` with sandboxing, a network allowlist, credential protections, and local data retention. For managed MCP servers, which you deploy alongside any of these through `managed-mcp.json` or provide through the [`managedMcpServers`](</docs/en/settings-reference#managedmcpservers>) key, see [Managed MCP configuration](</docs/en/managed-mcp>). ### @@ -136,7 +136,7 @@ Claude Code checks the sources in this order, highest priority first: - 1. Remote settings, delivered from claude.ai as [server-managed settings](</docs/en/server-managed-settings>) or by a [Claude apps gateway](</docs/en/claude-apps-gateway>). Claude Code fetches this source only when the session authenticates to Anthropic’s API directly with an [eligible credential](</docs/en/server-managed-settings#platform-availability>), or signs in to a gateway with `/login`. On other providers, or when `ANTHROPIC_BASE_URL` points somewhere other than Anthropic’s API, it starts at the next source + 1. Remote settings, delivered from claude.ai as [server-managed settings](</docs/en/server-managed-settings>) or by a [Claude apps gateway](</docs/en/claude-apps-gateway>). Claude Code fetches this source only when the session authenticates to Anthropic’s API directly with an [eligible credential](</docs/en/server-managed-settings#platform-availability>), signs in to a gateway with `/login`, or runs in Claude Desktop’s Code tab behind a gateway that [serves that session settings](</docs/en/claude-apps-gateway-config#apply-code-settings-in-the-code-tab>). On other providers, or when `ANTHROPIC_BASE_URL` points somewhere other than Anthropic’s API, it starts at the next source 2. MDM or OS-level policies: the macOS plist or the HKLM registry key 3. Managed settings files, `managed-settings.d/*.json` and `managed-settings.json` merged together 4. The HKCU registry, on Windows, and on WSL once the HKLM registry or the Windows managed settings file turns [`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>) on and the HKCU value also sets it. Claude Code reads it only when no admin document is present above it and no host-supplied parent settings supply a restrictive key
modified Plugin manifest reference View current →
--- a/manifest-reference.md +++ b/manifest-reference.md @@ -167,7 +167,7 @@ Puts `official` beside `claude` or `anthropic`, such as `official-claude-tools`| Error Has `claude`, `anthropic`, or `anthropics` as a whole word anywhere else, such as `mcp-for-claude`| Warning -The error reads `Plugin name "<name>" is reserved: it passes as one of Anthropic's own`, and the warning reads `Plugin name "<name>" reads as one of Anthropic's own`. `claude plugin init` and `claude plugin tag` refuse a name that draws the error. Only these commands check the name. Claude Code still installs and loads a plugin whose name they refuse. +The error reads `Plugin name "<name>" is reserved: it passes as one of Anthropic's own`, and the warning reads `Plugin name "<name>" reads as one of Anthropic's own`. `claude plugin init` and `claude plugin tag` refuse a name that draws the error. Claude Code still installs and loads a plugin whose name they refuse. ###
modified Marketplace reference View current →
--- a/marketplace-reference.md +++ b/marketplace-reference.md @@ -50,7 +50,7 @@ Field| Type| Description ---|---|--- -`name`| string| Marketplace identifier: letters, digits, `.`, `_`, and `-`, starting with a letter or digit, and no `..`. `claude plugin validate` fails any other name, because Claude Code can’t install plugins from a marketplace that uses one. Users type the name after `@` in a [plugin id](</docs/en/plugins/loading#find-where-a-plugin-came-from>) such as `my-plugin@my-marketplace` when they install a plugin. See Reserved names +`name`| string| Marketplace identifier: letters, digits, `.`, `_`, and `-`, starting with a letter or digit, and no `..`. `claude plugin validate` fails any other name, because Claude Code [can’t install plugins from a marketplace that uses one](</docs/en/plugins/troubleshooting#cannot-install-plugins-from-a-marketplace-with-this-name>). Users type the name after `@` in a [plugin id](</docs/en/plugins/loading#find-where-a-plugin-came-from>) such as `my-plugin@my-marketplace` when they install a plugin. See Reserved names `owner`| object| Maintainer information. `name` is required; `email` and `url` are optional `plugins`| array| Plugin entries. Each entry is validated on its own, so one invalid entry doesn’t fail the marketplace `$schema`| string| JSON Schema URL for editor autocomplete. Ignored at load time
modified Connect to external tools with MCP View current →
--- a/mcp.md +++ b/mcp.md @@ -70,7 +70,7 @@ ​ -In code +Add a server in code Pass MCP servers directly in the `mcpServers` option. This example starts a local filesystem MCP server for `/Users/me/projects`. Replace that path with a directory on your machine: @@ -125,7 +125,7 @@ ​ -From a config file +Add a server from a config file Create a `.mcp.json` file at your project root. The file is picked up when the `project` setting source is enabled, which it is for default `query()` options. If you set `settingSources` explicitly, include `"project"` for this file to load. Replace `/Users/me/projects` with a directory on your machine: @@ -283,7 +283,7 @@ stdio servers -Local processes that communicate via stdin/stdout. Use this for MCP servers you run on the same machine. For the `.mcp.json` form, use the same fields shown at From a config file. In code, pass the command and its arguments. Replace `/Users/me/projects` with a directory on your machine: +Local processes that communicate via stdin/stdout. Use this for MCP servers you run on the same machine. For the `.mcp.json` form, use the same fields shown at Add a server from a config file. In code, pass the command and its arguments. Replace `/Users/me/projects` with a directory on your machine: TypeScript
modified Migrate to Claude Agent SDK View current →
--- a/migration-guide.md +++ b/migration-guide.md @@ -28,7 +28,7 @@ ​ -For TypeScript/JavaScript Projects +Migrate a TypeScript or JavaScript project **1\. Uninstall the old package:** @@ -52,7 +52,7 @@ ​ -For Python Projects +Migrate a Python project **1\. Uninstall the old package:**
modified Monitoring View current →
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1080,7 +1080,7 @@ At mention event -Logged when Claude Code resolves an `@`-mention in a prompt. Not every mention emits an event: early-exit paths such as permission denials, oversized files, PDF reference attachments, and directory listing failures return without logging. **Event Name** : `claude_code.at_mention` **Attributes** : +Logged when Claude Code resolves an `@`-mention in a prompt. Not every mention emits an event: early-exit paths such as permission denials, oversized files, PDF reference attachments, and directory listing failures return without logging. Each time Claude Code reads a prompt, it logs at most 100 events with a `mention_type` of `"agent"` and 100 with `"mcp_resource"`. Mentions past either limit still resolve but emit no event. **Event Name** : `claude_code.at_mention` **Attributes** : * All standard attributes * `event.name`: `"at_mention"` @@ -1569,7 +1569,7 @@ ​ -For metrics +Backends for metrics * **Time series databases** : Rate calculations, aggregated metrics * **Columnar stores** : Complex queries, unique user analysis @@ -1579,7 +1579,7 @@ ​ -For events/logs +Backends for events and logs * **Log aggregation systems** : Full-text search, log analysis * **Columnar stores** : Structured event analysis @@ -1589,7 +1589,7 @@ ​ -For traces +Backends for traces Choose a backend that supports distributed trace storage and span correlation:
modified Publish and distribute a plugin View current →
--- a/publish.md +++ b/publish.md @@ -120,7 +120,7 @@ ] } -In your shell, run `claude plugin validate .` in the repository to check the file before you push. [Create a marketplace](</docs/en/plugins/create-marketplace>) covers the layout with several plugins in one repository. +In your shell, run `claude plugin validate .` in the repository before you push. For what the run checks, see [Validate a directory](</docs/en/plugins/cli-reference#validate-a-directory>). [Create a marketplace](</docs/en/plugins/create-marketplace>) covers the layout with several plugins in one repository. ###
modified Mods reference View current →
--- a/reference.md +++ b/reference.md @@ -60,7 +60,7 @@ ---|---|--- [`tool.call`](</docs/en/plugins/mods/events#guard-or-change-a-tool-call>)| A tool is about to run| `next(e)`, `{ deny: reason }`, or `{ result }` [`tool.check`](</docs/en/plugins/mods/events#where-settings-hooks-run-in-the-order>)| Claude Code decides whether a tool call may run, after the `tool.call` and `PreToolUse` hooks. `next(e)` resolves to the decision the rules, the permission mode, and those hooks reached.| `{ decision }`, which is `allow`, `ask`, or `deny` -`tool.describe`| Once for each tool, when its description is first sent to Claude| `{ description }`, optionally with `isDeferred` set to `true` to put the tool behind [tool search](</docs/en/mcp#scale-with-mcp-tool-search>) or `false` to load it upfront +`tool.describe`| Once for each tool, when its description is first sent to Claude. A second time for an MCP tool when Claude loads it through [tool search](</docs/en/mcp#scale-with-mcp-tool-search>), with `e.description` set to the text Claude reads for the loaded tool.| `{ description }`, optionally with `isDeferred` set to `true` to put the tool behind tool search or `false` to load it upfront #### @@ -139,7 +139,7 @@ `session.end`| The session ends, or `/clear`, `/resume`, or `/branch` runs. `e.reason` is `clear`, `resume`, `logout`, `prompt_input_exit`, or `other`. `/branch` reports `resume`.| `next(e)` `session.compact`| The conversation is about to be compacted| `{ skip: reason }` [`session.receive`](</docs/en/plugins/mods/api#send-and-receive-messages-between-sessions>), [`session.send`](</docs/en/plugins/mods/api#send-and-receive-messages-between-sessions>)| A message arrives from, or is about to go to, another agent or session. See [Send and receive messages between sessions](</docs/en/plugins/mods/api#send-and-receive-messages-between-sessions>).| `{ consumed: reason }` for `receive`, `{ isDelivered: false, reason }` for `send` -`session.append`| Once for each row the conversation keeps, such as a prompt, a response block, a tool result, or a notice, before it’s stored| `next({ ...e, message })` to rewrite the row’s `content` +`session.append`| Once for each row the conversation keeps, such as a prompt, a response block, a tool result, or a notice, before it’s stored| `next({ ...e, message })` with a changed `message.content`, to rewrite the row’s text blocks or the `content` of a `tool_result` block in it `session.attach`, `session.detach`| Another app connects to or disconnects from the session| `next(e)` `session.measure`| After each turn, and when a plan limit’s percent used changes| `next(e)` @@ -352,6 +352,7 @@ `$.ui.invalidate('ui.render')` redraws| Throttled to 10 a second, or 30 in the terminal for the visible pane, the expanded band, and the hint line under the prompt. Calls that come sooner are coalesced. `$.ui.toast`| Shown for 4 seconds unless you pass `{ timeoutMs }` A pane opened without the user asking| Placed from 144 terminal columns, 110 after they’ve opened it once +Scopes, such as functions, blocks, and loops, nested inside one another in one file of a hooks module| 2,000 Command, tool, subagent type, and pane names| Letters, digits, `_`, and `-`, up to 64 characters One `claude plugin test` test| 5 seconds unless the test sets `timeoutMs`
modified Continue local sessions from any device with Remote Control View current →
--- a/remote-control.md +++ b/remote-control.md @@ -336,13 +336,46 @@ * **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. `/claude-api` is also unavailable when you type it from mobile or web. Claude can still [load that skill on its own](</docs/en/skills#work-on-claude-api-projects>) there. The following work from mobile and web: * Text-output commands: `/compact`, `/clear`, `/context`, `/usage`, `/exit`, `/usage-credits`, `/recap`, and `/reload-plugins`. `/usage-credits` prints the billing URL instead of opening a browser. `/reload-plugins` works only when the session runs in an interactive terminal; a session without one declines it. * `/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. - * `/mcp`: from the mobile app, returns a text summary of server status instead of opening the picker. On the web, `/mcp` on its own opens a directory of [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) instead of returning the summary. The `reconnect`, `enable`, and `disable` [subcommands](</docs/en/commands#all-commands>) work from both. `/mcp reconnect` with no server name retries every server that has failed or needs authentication. + * `/mcp`: from the mobile app, returns a text summary of server status instead of opening the picker. On the web, `/mcp` on its own opens a directory of [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) instead of returning the summary. The `reconnect`, `enable`, and `disable` [subcommands](</docs/en/commands#all-commands>) work from both when the session runs in an interactive terminal. `/mcp reconnect` with no server name retries every server that has failed or needs authentication. To authorize a claude.ai connector without the picker, see Authorize a connector again from your shell. * `/config`: from the mobile app, pass `key=value` to set a setting, or run it with no argument to list the keys you can set. On the web, `/config` opens the Claude Code section of your settings instead, and ignores text after the command. * On Team and Enterprise, `/usage-credits` from mobile or web doesn’t send a [usage-credits request to your admin](</docs/en/costs#add-usage-credits-to-your-subscription>). Sending requires a confirmation that appears only in the interactive CLI, so the command tells you to run it there instead. * `/autocompact`, from v2.1.221: pass the window size as an argument, for example `/autocompact 500k`. With no argument, it prints the current window size as text instead of opening the dialog the command shows in a terminal session. * `/advisor`, from v2.1.260: pass the model as an argument, for example `/advisor opus`, or pass `off` to turn the advisor off. Both forms apply to the current session only and leave your saved default unchanged. With no argument, it prints the current advisor as text instead of opening the picker. * `/output-style`, from v2.1.269: pass the style name as an argument, for example `/output-style concise`, or run it with no argument to list the styles. From mobile and web, you can list and select only [built-in styles](</docs/en/output-styles#built-in-output-styles>). To use a [custom style](</docs/en/output-styles#create-a-custom-output-style>), select it in the session itself. * `/focus`, from v2.1.281: pass `on` or `off` as an argument, for example `/focus on`, or run it with no argument to toggle the [focus view](</docs/en/commands#all-commands>). Both forms apply to the current session only and leave your saved selection unchanged. + +## + +​ + +Authorize a connector again from your shell + +When a claude.ai connector needs authentication in a session you drive over Remote Control, the `/mcp` panel isn’t available from the mobile app or the web. Get the authorization link from a terminal on the machine where the session runs, then open the link on the device you’re using. You can’t run the command from the mobile app or the web. A line you send from there that starts with `!` goes to Claude as a message and doesn’t run in [shell mode](</docs/en/interactive-mode#shell-mode-with-prefix>). + +1 + +Get the authorization link + +In a terminal on the machine where the session runs, such as over SSH, run `claude mcp login` with the connector’s name in quotes. A connector’s name starts with `claude.ai`, such as `claude.ai Slack` for the Slack connector. The following command gets the link for the Slack connector: + + claude mcp login "claude.ai Slack" --no-browser + +The command prints a claude.ai link and exits. Open the link in your browser and finish authorizing on claude.ai. `--no-browser` keeps the command from opening a browser on that machine, which might not be the device you’re using. + +2 + +Use the connector in a session + +Start a new session, or reconnect the connector in the session that’s already running: + + * **New session** : a session you start after authorizing connects to the connector without any further step. + * **Running session** : run `/mcp reconnect` with the same name and no quotes, at the Claude Code prompt or from the mobile app or the web. To check that your session accepts the command from there, see the `/mcp` entry under which commands work from mobile and web. + +The following command reconnects the Slack connector: + + /mcp reconnect claude.ai Slack + +In the terminal, Claude Code prints `Successfully reconnected to claude.ai Slack`. From the mobile app or the web, the reply is `Reconnected "claude.ai Slack".` ##
modified Run prompts on a schedule View current →
--- a/scheduled-tasks.md +++ b/scheduled-tasks.md @@ -169,12 +169,31 @@ Jitter -To avoid every session hitting the API at the same wall-clock moment, the scheduler adds a deterministic offset to fire times: - - * Recurring tasks fire up to 30 minutes after the scheduled time (or up to half the interval, for tasks that run more often than hourly). An hourly job scheduled for `:00` may fire anywhere up to `:30`. - * One-shot tasks scheduled for the top or bottom of the hour fire up to 90 seconds early. - -The offset is derived from the task ID, so the same task always gets the same offset. If exact timing matters, pick a minute that is not `:00` or `:30`, for example `3 9 * * *` instead of `0 9 * * *`, and the one-shot jitter will not apply. +A scheduled task can run at a different time than its schedule says. If every session’s tasks ran exactly on schedule, many of them would call the API at the same moment, so Claude Code shifts each task’s run time. Recurring tasks run late, and one-shot tasks scheduled on the hour or half hour run a little early. + +#### + +​ + +How late a recurring task runs + +When you create a recurring task, Claude Code gives it a fixed delay and adds that delay to every run. The delay is worked out from the task’s ID, so the same task runs the same number of minutes late each time, including when the session is idle and nothing else is running. Tasks that run more often get shorter delays, and 30 minutes is the longest delay a task can get. These are the delay ranges for some common schedules: + +Task runs| Delay is between +---|--- +Every 10 minutes| 0 and 5 minutes +Every 30 minutes| 0 and 15 minutes +Every hour, or less often such as daily| 0 and 30 minutes + +For example, `7,37 * * * *` schedules a task for `:07` and `:37`, which are 30 minutes apart, so its delay is somewhere between 0 and 15 minutes. If this task’s delay is 14 minutes, it runs at `:21` and `:51` every hour. Changing the schedule to a different minute moves the run time, and a delay is still added on top. + +#### + +​ + +When a one-shot task runs early + +A one-shot task scheduled for `:00` or `:30` runs up to 90 seconds early. Claude Code doesn’t shift a one-shot task scheduled for any other minute, so when the timing matters, schedule it off the hour and half hour: `3 9 * * *` instead of `0 9 * * *`. ###
modified Catch security issues as Claude writes code View current →
--- a/security-guidance.md +++ b/security-guidance.md @@ -70,7 +70,7 @@ ​ -On each file edit +Checks on each file edit When Claude writes to a file, the plugin scans the new content for known risky patterns. This is a pattern match with no model call, so it adds no usage cost. Example pattern categories: @@ -85,7 +85,7 @@ ​ -At the end of each turn +Checks at the end of each turn A turn is one round of Claude responding: you send a message, Claude works and replies, and the turn ends. After each turn, the plugin computes a git diff of everything that changed in the working tree during the turn, including changes from Claude’s edit tools, Bash commands, and subagents, and sends it to a separate Claude review focused on security. The review runs in the background, so Claude’s reply is not delayed. If the review finds issues, Claude is re-prompted with the findings and addresses them as a follow-up. This catches issues a string match cannot, such as: @@ -101,7 +101,7 @@ ​ -On each commit or push Claude makes +Checks on each commit or push Claude makes When Claude runs `git commit` or `git push` through its Bash tool, the plugin runs a deeper agentic review of the change in the background. This review reads surrounding code, including callers, sanitizers, and related files, to decide whether a finding is real before reporting it. The extra context keeps false positives low on patterns that look dangerous in isolation but are safe in your codebase. This layer fires only on commits and pushes Claude makes through its Bash tool. Commits you run from your own shell, including the `!` shell escape inside a session, are not reviewed. Commit and push reviews are capped at 20 per rolling hour. If the commit review’s findings duplicate what the end-of-turn review already reported, Claude is not re-prompted, so a clean commit produces no visible output from this layer.
modified Self-hosted environments View current →
--- a/self-hosted-environments.md +++ b/self-hosted-environments.md @@ -120,11 +120,11 @@ The runner and its sessions make several kinds of outbound connection, and no inbound connectivity from Anthropic is required: * **Control plane** : the runner polls `api.anthropic.com` for work and posts setup-progress and failure events, all outbound HTTPS. Polling doubles as the runner’s heartbeat. - * **SCM connector** : the optional orchestrator [SCM connector](</docs/en/self-hosted-environments-reference#scm-connector-flags>) tunnel is the only WebSocket connection. - * **Git** : the runner clones from and pushes to your git host over HTTPS or SSH, authenticated with credentials your deployment provides; [Configure git](</docs/en/self-hosted-environments-deploy#configure-git>) covers the options, including per-session minted credentials and the [Anthropic git proxy](</docs/en/self-hosted-environments-deploy#use-the-anthropic-git-proxy>), which routes git through `api.anthropic.com` instead. - * **Session child** : the child Claude Code process holds the session’s event stream to `api.anthropic.com`, and makes its own outbound calls for model inference and for git commands run during the session. See [Network requirements](</docs/en/self-hosted-environments-deploy#network-requirements>) for the full egress list. The diagram above shows these paths, apart from the optional SCM connector. + * **Git** : the runner clones from and pushes to your git host over HTTPS or SSH, authenticated with credentials your deployment provides. See [Configure git](</docs/en/self-hosted-environments-deploy#configure-git>) for the options, including per-session minted credentials. With the [Anthropic git proxy](</docs/en/self-hosted-environments-deploy#use-the-anthropic-git-proxy>), git traffic for repositories on github.com goes through `api.anthropic.com` instead. + * **Session child** : the child Claude Code process holds the session’s event stream to `api.anthropic.com`, and makes its own outbound calls for model inference and for git commands run during the session. In a session that uses [Anthropic-managed git](</docs/en/self-hosted-environments-deploy#use-the-anthropic-git-proxy>), the child sends its `git` and `gh` traffic for github.com over a WebSocket connection it opens to `api.anthropic.com`. + * **SCM connector** : the optional orchestrator [SCM connector](</docs/en/self-hosted-environments-reference#scm-connector-flags>) isn’t available, so its tunnel doesn’t open. The tunnel is a WebSocket connection to `api.anthropic.com`. -By default, model inference uses the Anthropic API. The control plane delivers the API endpoint to each session, and the session authenticates with an Anthropic-issued, session-scoped OAuth token. To send model requests to your own cloud account instead, see [Send model requests to Bedrock or Agent Platform](</docs/en/self-hosted-environments-configuration#send-model-requests-to-bedrock-or-agent-platform>). Corporate egress proxies are supported. The runner and the optional [autoscaling orchestrator](</docs/en/self-hosted-environments-configuration#on-demand-runners>) honor the proxy and mTLS environment variables described in [Network configuration](</docs/en/network-config>), such as `HTTPS_PROXY` and `NO_PROXY`; set them in each process’s environment. The variables cover control-plane calls, the orchestrator’s [SCM connector](</docs/en/self-hosted-environments-reference#scm-connector-flags>) WebSocket, and the built-in clone for HTTPS remotes, and sessions inherit them from the runner. Session streaming uses server-sent events over HTTPS, so a proxy in the path must not buffer responses. If your proxy also requires a `Proxy-Authorization` header, the runner can add it to each connection it opens to the proxy; see [Authenticate to an egress proxy](</docs/en/self-hosted-environments-deploy#authenticate-to-an-egress-proxy>). +See [Network requirements](</docs/en/self-hosted-environments-deploy#network-requirements>) for the full egress list. The diagram above shows these paths, apart from the optional SCM connector and the Anthropic-managed git connection. By default, model inference uses the Anthropic API. The control plane delivers the API endpoint to each session, and the session authenticates with an Anthropic-issued, session-scoped OAuth token. To send model requests to your own cloud account instead, see [Send model requests to Bedrock or Agent Platform](</docs/en/self-hosted-environments-configuration#send-model-requests-to-bedrock-or-agent-platform>). Corporate egress proxies are supported. The runner and the optional [autoscaling orchestrator](</docs/en/self-hosted-environments-configuration#on-demand-runners>) honor the proxy and mTLS environment variables described in [Network configuration](</docs/en/network-config>), such as `HTTPS_PROXY` and `NO_PROXY`; set them in each process’s environment. The variables cover control-plane calls, the orchestrator’s [SCM connector](</docs/en/self-hosted-environments-reference#scm-connector-flags>) WebSocket, and the built-in clone for HTTPS remotes, and sessions inherit them from the runner. Session streaming uses server-sent events over HTTPS, so a proxy in the path must not buffer responses. If your proxy also requires a `Proxy-Authorization` header, the runner can add it to each connection it opens to the proxy; see [Authenticate to an egress proxy](</docs/en/self-hosted-environments-deploy#authenticate-to-an-egress-proxy>). ##
modified Customize sessions in self-hosted environments View current →
Show diff (272 lines)
--- a/self-hosted-environments-configuration.md +++ b/self-hosted-environments-configuration.md @@ -17,17 +17,30 @@ Variable| Description ---|--- `CLAUDE_CODE_SESSION_ACCESS_TOKEN`| The session JWT, prefixed `sk-ant-cc-`. Its `act` claim identifies the session creator, with the creator’s email when the creating surface recorded it. The value is the token at spawn time; refreshes arrive over the child’s stdin, so a wrapper sees only the initial value. See [Verify session identity](</docs/en/self-hosted-environments-identity>). -`CCR_SESSION_ACCOUNT_EMAIL`| The session creator’s email, pre-extracted by the runner from the token’s `act.email` claim without signature verification. Suitable for labelling, such as commit trailers. When the email gates credential issuance, verify the token and read the claim from it instead; see Provision credentials scoped to the session creator. Unset when the token carries no creator email. Treat as personally identifiable information. -`CLAUDE_RUNNER_CLIENT_PLATFORM`| The client surface that created the session, such as `web_claude_ai`, `desktop_app`, `ios`, `claude_code_cli`, or `scheduled_trigger`. Anthropic records the value once at session creation, so the wrapper and every lifecycle hook see the same value. Use it for adoption analytics and labelling only, not as an authorization signal. Unset when the session has no recorded or recognized surface, so reference it as `${CLAUDE_RUNNER_CLIENT_PLATFORM:-}` under `set -u`. Requires Claude Code v2.1.229 or later. +`CCR_SESSION_ACCOUNT_EMAIL`| The session creator’s email, pre-extracted by the runner from the token’s `act.email` claim without signature verification. Suitable for labelling, such as commit trailers. When the email gates credential issuance, verify the token and read the claim from it instead. See Provision credentials scoped to the session creator. Unset when the token carries no creator email, for example in sessions your organization’s service identity creates. Treat as personally identifiable information. +`CLAUDE_RUNNER_CLIENT_PLATFORM`| The client surface that created the session, such as `web_claude_ai`, `desktop_app`, `ios`, `claude_code_cli`, or `scheduled_trigger`. Anthropic records the value once at session creation, so the wrapper and every lifecycle hook see the same value. Use it for adoption analytics and labelling only, not as an authorization signal. Unset when the session has no recorded or recognized surface. Requires Claude Code v2.1.229 or later. `CLAUDE_RUNNER_CLAUDE_BIN`| Absolute path to the runner’s own Claude Code binary. End your wrapper with `exec "$CLAUDE_RUNNER_CLAUDE_BIN" "$@"` to pass control to the pinned binary without hardcoding an install path. `CLAUDE_CODE_REMOTE_SESSION_ID`| Session ID in the tagged `cse_...` form. This is the same session the lifecycle hooks see as `CLAUDE_RUNNER_SESSION_ID` in `session_...` form; the UUID variables match across both, and substituting the `cse_` prefix with `session_` yields the ID shown in the session URL. `CLAUDE_CODE_REMOTE_SESSION_UUID`| The same session ID in canonical UUID form, for systems that key on UUIDs. +`CLAUDE_CODE_REMOTE_SLACK_THREAD_URL`| For a [Claude Tag](<https://claude.com/docs/claude-tag/overview>) session that belongs to one Slack thread, the link to that thread. Unset for other sessions, and can be unset for a thread session too. +`CLAUDE_CODE_REMOTE_SLACK_THREAD_TS`| For a Claude Tag session that belongs to one Slack thread, that thread’s Slack timestamp, such as `1700000000.000100`. Can be unset, and can be set when `CLAUDE_CODE_REMOTE_SLACK_THREAD_URL` isn’t, so check each variable on its own. `CLAUDE_SESSION_INGRESS_TOKEN_FILE`| Absolute path to a per-session file holding the current session JWT, kept fresh across token refreshes. Shell subprocesses read it for their `Authorization` header when downloading attachments the user added to the session. `exec` preserves the variable automatically; a wrapper that rebuilds the child’s environment must carry the variable over, or attachment downloads silently stop working. `CLAUDE_CONFIG_DIR`| Per-session Claude config directory, written at session start from the snapshot of the runner host’s config that the runner captures at startup; see Permissions and tool approval. Writes here are isolated to this session. The directory stays under `<base-dir>/_sessions/` after the session ends unless you start the runner with [`--remove-session-state`](</docs/en/self-hosted-environments-reference#runner-cli-flags>); see [Reuse a pre-warmed checkout](</docs/en/self-hosted-environments-deploy#reuse-a-pre-warmed-checkout>). `ANTHROPIC_BASE_URL`| The API base URL the child will use, delivered by the control plane per session and normally `https://api.anthropic.com`. Don’t override it: the session’s inference credential is an Anthropic-issued OAuth token that other providers don’t accept. `CLAUDE_CODE_OAUTH_TOKEN`| The short-lived OAuth access token the child uses for model inference, scoped to model inference and file upload only, with a lifetime of about 30 minutes. The runner re-mints it before expiry and delivers the rotation over the child’s stdin, so a wrapper that doesn’t keep stdin attached sees only the initial value. Don’t rely on your organization’s IP allowlist to bound this token’s use: treat it as a bearer credential that stays usable for roughly 30 minutes if it leaks, and don’t log it, write it to disk, or forward it outside the session container. -The wrapper also inherits the rest of the child’s managed environment, including any server-provided environment variables. `exec` propagates all of it automatically; if your wrapper spawns the child another way, forward the full environment. +The wrapper also inherits the rest of the child’s managed environment, including any server-provided environment variables. `exec` propagates all of it automatically; if your wrapper spawns the child another way, forward the full environment. `CLAUDE_CODE_REMOTE_SLACK_THREAD_URL` and `CLAUDE_CODE_REMOTE_SLACK_THREAD_TS` reach your wrapper or `command` hook. They also reach what the session runs, such as shell commands, git hooks, and Claude Code hooks. The `checkout`, `post-session`, and `spawn-runner` hooks don’t receive them. + +### + +​ + +Give a default to variables that can be unset + +`CCR_SESSION_ACCOUNT_EMAIL`, `CLAUDE_RUNNER_CLIENT_PLATFORM`, `CLAUDE_CODE_REMOTE_SLACK_THREAD_URL`, and `CLAUDE_CODE_REMOTE_SLACK_THREAD_TS` can each be unset. If your script uses `set -u`, Bash stops with `unbound variable` when it expands one that’s unset, so expand them with a default, such as `${CCR_SESSION_ACCOUNT_EMAIL:-}`. Wherever a shell expands the Slack thread link, take these precautions: + + * **Quote it** : the link can contain characters a shell acts on, such as `?` and `&`, so quote the variable, as in `"${CLAUDE_CODE_REMOTE_SLACK_THREAD_URL:-}"`. + * **Keep its value out of`eval` and `sh -c` strings**: don’t substitute its value into a string that `eval` or `sh -c` runs, even inside quotes. Have that string reference the variable instead. ### @@ -35,7 +48,7 @@ Keep stdin and file descriptor 3 attached -The child’s stdin is the runner’s control channel. Token rotations and session-end signals arrive on it. The runner also opens a pipe on file descriptor 3 and reads the child’s activity signals from it to drive idle and startup timeouts. A plain `exec "$CLAUDE_RUNNER_CLAUDE_BIN" "$@"` preserves both automatically. If your wrapper backgrounds the child with a bare `&`, it severs the child’s stdin: the session looks healthy until the initial OAuth token’s roughly 30-minute lifetime expires, then every API call fails with `401 authentication_error`. If your wrapper must background the child, for example to keep a teardown trap alive, save stdin on file descriptor 4 or higher and re-attach it explicitly: +The child’s stdin is the runner’s control channel. Token rotations and session-end signals arrive on it. The runner also opens a pipe on file descriptor 3 and reads the child’s activity signals from it to drive idle and startup timeouts. A plain `exec "$CLAUDE_RUNNER_CLAUDE_BIN" "$@"` preserves both automatically. If your wrapper backgrounds the child with a bare `&`, it severs the child’s stdin. The session looks healthy until the initial OAuth token’s roughly 30-minute lifetime expires, and then every API call that uses the token fails with `401 authentication_error`. If your wrapper must background the child, for example to keep a teardown trap alive, save stdin on file descriptor 4 or higher and re-attach it explicitly: exec 4<&0 "$CLAUDE_RUNNER_CLAUDE_BIN" "$@" <&4 4<&- & @@ -43,7 +56,10 @@ trap 'teardown' EXIT wait "$CHILD" -Don’t close or reuse file descriptor 3 in the wrapper. Redirecting the child’s stdout and stderr is fine. +You can redirect the child’s stdout. Keep file descriptor 3 and stderr attached to the runner: + + * **File descriptor 3** : carries the child’s activity signals to the runner. Don’t close it or reuse it in the wrapper. + * **stderr** : when the wrapper or the child exits non-zero, the runner posts the last lines of stderr to the session and prints them in its own log. The session’s user sees those lines, so don’t print secrets to stderr, and remove `set -x` before you deploy the wrapper. If you redirect stderr, sessions still run, but the runner reports a failure with the exit code alone. ### @@ -92,26 +108,45 @@ checkout -Runs once per repository, in place of the runner’s built-in clone and fetch. Use the hook to clone from a read-through mirror, seed a working tree from an archive, or apply per-session git auth. The runner sets these variables, and may set other `CLAUDE_RUNNER_` variables that the table doesn’t list: +Runs once per repository, in place of the runner’s built-in clone and fetch. Use the hook to clone from a read-through mirror that you reach over HTTPS or SSH, seed a working tree from an archive, or apply per-session git auth. The runner sets these variables, and may set other `CLAUDE_RUNNER_` variables that the table doesn’t list: Variable| Description ---|--- `CLAUDE_RUNNER_REPO_URL`| Repository URL to clone, after any `--git-host-rewrite` and `--git-ssh-rewrite` have been applied -`CLAUDE_RUNNER_REPO_REF`| Revision to check out: branch, tag, or commit SHA as the session requested it. Empty means the repository’s default branch. +`CLAUDE_RUNNER_REPO_REF`| Revision to check out, as the session requested it: a branch, tag, commit SHA, or full reference name such as `refs/pull/<number>/head`. Empty means the repository’s default branch. `CLAUDE_RUNNER_CHECKOUT_PATH`| Absolute path where the working tree must be left `CLAUDE_RUNNER_SESSION_ID`| Session ID in the tagged `session_...` form, for logging and correlation `CLAUDE_RUNNER_SESSION_UUID`| The same session ID in canonical UUID form `CLAUDE_RUNNER_API_BASE_URL`| Anthropic API base URL for session-scoped calls -`CLAUDE_RUNNER_CLIENT_PLATFORM`| The client surface that created the session, such as `web_claude_ai`, `desktop_app`, or `ios`. Unset when the session has no recorded or recognized surface. +`CLAUDE_RUNNER_CLIENT_PLATFORM`| The client surface that created the session, such as `web_claude_ai`, `desktop_app`, or `ios`. Unset when the session has no recorded or recognized surface, so reference it as `${CLAUDE_RUNNER_CLIENT_PLATFORM:-}` under `set -u`. Requires Claude Code v2.1.229 or later. `CLAUDE_CODE_SESSION_ACCESS_TOKEN`| The session access token, for session-scoped API calls `GIT_CONFIG_COUNT`, `GIT_CONFIG_KEY_n`, `GIT_CONFIG_VALUE_n`| Git settings the runner fixes for the git your hook runs. Git configuration inside lifecycle hooks describes them. Requires Claude Code v2.1.280 or later. -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: +The script must leave a working tree at `CLAUDE_RUNNER_CHECKOUT_PATH` checked out at the requested revision. A detached HEAD works, because the runner creates the session’s working branch on top. After your hook returns, the runner verifies that `CLAUDE_RUNNER_CHECKOUT_PATH` contains a `.git`. 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. + +#### + +​ + +Get git credentials in the hook + +The runner doesn’t pass a git credential to the hook. The `decode-token` subcommand isn’t available here either, because `CLAUDE_RUNNER_CLAUDE_BIN` isn’t set in the checkout-hook environment. Mint a per-session clone credential from the session’s identity instead, or fall back to the host’s own git authentication: + + * **Per-session clone credential** : 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. Key that credential on `act.sub`, and don’t require `act.email`. + * **Host git authentication** : use whatever git authentication the host already has, such as an SSH agent, credential helper, or `.netrc`. + +#### + +​ + +When the hook fails + +The hook fails when it exits non-zero, or exits 0 without leaving a usable checkout behind: * **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. + * **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. If skipping leaves the session with no repository at all, the runner fails the session anyway. + +When the hook succeeds, the runner removes the checkout path after the session ends. ### @@ -129,21 +164,28 @@ `CLAUDE_RUNNER_WORKSPACE_PATHS`| Colon-separated absolute paths of the session’s working trees. Empty for zero-repo sessions. `CLAUDE_RUNNER_DEBUG_LOG_PATH`| Path to the session’s debug log, still on disk while the hook runs `CLAUDE_RUNNER_API_BASE_URL`| Anthropic API base URL for session-scoped calls -`CLAUDE_RUNNER_CLIENT_PLATFORM`| The client surface that created the session, such as `web_claude_ai`, `desktop_app`, or `ios`. Unset when the session has no recorded or recognized surface. Requires Claude Code v2.1.229 or later. +`CLAUDE_RUNNER_CLIENT_PLATFORM`| The client surface that created the session, such as `web_claude_ai`, `desktop_app`, or `ios`. Unset when the session has no recorded or recognized surface, so reference it as `${CLAUDE_RUNNER_CLIENT_PLATFORM:-}` under `set -u`. Requires Claude Code v2.1.229 or later. `CLAUDE_CODE_SESSION_ACCESS_TOKEN`| The session access token, for session-scoped API calls `GIT_CONFIG_COUNT`, `GIT_CONFIG_KEY_n`, `GIT_CONFIG_VALUE_n`| Git settings the runner fixes for the git your hook runs. Git configuration inside lifecycle hooks describes them. Requires Claude Code v2.1.280 or later. `CLAUDE_RUNNER_EXIT_REASON` takes one of four values: - * `completed`: the session ended cleanly. The Claude Code process exited normally, or the session was archived or deleted while it was still running. + * `completed`: the session ended cleanly. The Claude Code process exited normally, or exited by itself after the session was archived or deleted. * `failed`: the Claude Code process crashed, or setup failed after it started. - * `interrupted`: the runner stopped the session. It released the session to free the slot, the session timed out at startup, the server moved the session off this runner, the runner was draining, or the session outlasted its [`--kill-session-after-min`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) limit. + * `interrupted`: the runner stopped the session, in one of these cases: + * The runner released the session to free the slot. + * The session timed out at startup. + * The server moved the session off this runner. + * The runner’s poll noticed an archive or delete before the process exited. + * The runner was draining. + * The session outlasted its [`--kill-session-after-min`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) limit. * `abandoned`: reserved for a session another runner claimed. The hook doesn’t currently fire in that case. -The [session lifecycle counters](</docs/en/self-hosted-environments-reference#session-lifecycle-counter-semantics>) count a release, a startup timeout, and a server move as `completed` rather than `interrupted`, because the runner handed the slot back cleanly. Expect that difference if you compare hook receipts with the counters. The hook’s exit status never affects the session outcome; a failure is logged and ignored. The runner waits up to `--post-session-hook-timeout-sec`, 60 seconds by default, on every session end including runner shutdown. This example saves uncommitted work to a rescue branch: +If you compare hook receipts with the [session lifecycle counters](</docs/en/self-hosted-environments-reference#session-lifecycle-counter-semantics>), expect some `interrupted` receipts to count as `completed` there. The counters count a release, a startup timeout, a server move, and an archive or delete that the runner’s poll noticed first as `completed`, because the runner handed the slot back cleanly. The hook’s exit status never affects the session outcome; a failure is logged and ignored. The runner waits up to `--post-session-hook-timeout-sec`, 60 seconds by default, on every session end including runner shutdown. This example saves uncommitted work to a rescue branch: #!/usr/bin/env bash set -u + export GIT_ALLOW_PROTOCOL=${GIT_ALLOW_PROTOCOL:-https:http:ssh} IFS=':' # -c overrides beat repo-local settings, blocking session-written fsmonitor, # hook-path, and gpg-program config from executing code with the hook's @@ -162,7 +204,7 @@ g push -q origin "HEAD:refs/heads/rescue/$CLAUDE_RUNNER_SESSION_ID" || true done -The hook pushes with whatever git credentials are available in its own environment on the runner host. Under the [no-credentials-in-the-image posture](</docs/en/self-hosted-environments-deploy#configure-git>), including when the built-in clone goes through the Anthropic git proxy, there are none, so mint a short-lived push credential inside the hook before pushing: exchange the session token the hook receives in `CLAUDE_CODE_SESSION_ACCESS_TOKEN` with your own token service, verifying it as [Verify session identity](</docs/en/self-hosted-environments-identity>) describes. When the hook holds a credential the session didn’t, replace `origin` with an operator-supplied URL and pass `-c credential.helper=` plus your own helper. Git configuration inside lifecycle hooks describes what session-written configuration can still affect. +The `GIT_ALLOW_PROTOCOL` line in the script limits git to HTTPS, HTTP, and SSH remotes. If the runner’s environment already sets a non-empty `GIT_ALLOW_PROTOCOL` list of its own, the script keeps that list. The hook pushes with whatever git credentials are available in its own environment on the runner host. Under the [no-credentials-in-the-image posture](</docs/en/self-hosted-environments-deploy#configure-git>), including when the built-in clone goes through the Anthropic git proxy, there are none, so mint a short-lived push credential inside the hook before pushing: exchange the session token the hook receives in `CLAUDE_CODE_SESSION_ACCESS_TOKEN` with your own token service, verifying it as [Verify session identity](</docs/en/self-hosted-environments-identity>) describes. When the hook holds a credential the session didn’t, replace `origin` with an operator-supplied URL and pass `-c credential.helper=` plus your own helper. Git configuration inside lifecycle hooks describes what session-written configuration can still affect. #### @@ -236,13 +278,13 @@ `CLAUDE_RUNNER_ORDER_ID`| Opaque idempotency key, unique per spawn request and safe for Kubernetes resource names. Use only the order ID as your provisioner’s dedup key. `CLAUDE_RUNNER_SESSION_ID`| The session this request is for. It repeats on every re-request for the session, so use it for logging and routing, not as a dedup key. Empty for pre-warming requests, which boot a standby runner ahead of any specific session when [`--min-idle`](</docs/en/self-hosted-environments-reference#orchestrator-cli-flags>) is set, so don’t assume the variable is set. `CLAUDE_RUNNER_SESSION_UUID`| The same session ID in canonical UUID form. Empty for pre-warming requests. -`CLAUDE_RUNNER_ATTEMPT`| How many spawn requests this session has had. `0` for pre-warming requests. +`CLAUDE_RUNNER_ATTEMPT`| A per-session counter to use for logging. It isn’t a retry count or a request count. `0` for pre-warming requests, though a request for a session can carry `0` too. `CLAUDE_RUNNER_ORDER_SERVER_TIME`| Server time from the poll response’s HTTP `Date` header. When the hook verifies the work-order JWT’s `exp`, compare against this value instead of the local clock to tolerate skew. Empty when the gateway omitted the header. `CLAUDE_RUNNER_POOL_ID`| The ID of the environment the new runner should join, in `ccpool_...` form `CLAUDE_RUNNER_ACCOUNT_ID`| Tagged ID of the account that enqueued the session, for per-account routing, quota, or chargeback. Empty when unavailable, and always empty for Claude Tag channel sessions, which no account enqueues. `CLAUDE_RUNNER_ACCOUNT_EMAIL`| Email of the account that enqueued the session. Empty when unavailable. Treat the email as personally identifiable information and don’t log it. `CLAUDE_RUNNER_PRIMARY_REPO_URL`| URL of the session’s first git source, for routing to a runner with that repository pre-warmed. Empty when the session has no git sources. -`CLAUDE_RUNNER_PRIMARY_REPO_REVISION`| Revision of the session’s first git source: branch, SHA, or tag. Empty when unspecified. +`CLAUDE_RUNNER_PRIMARY_REPO_REVISION`| Revision of the session’s first git source: branch, SHA, tag, or full reference name. Empty when unspecified. `CLAUDE_RUNNER_REPO_SOURCES`| JSON array of `{url, revision}` for all the session’s git sources, for hooks that route on a secondary repository. Empty when there are no sources. `CLAUDE_RUNNER_CORRELATION_ID`| The correlation ID supplied at session create, echoed back so the hook can map this work order to the request that created the session. Empty when the session has none. `CLAUDE_RUNNER_CLIENT_PLATFORM`| The client surface that created the session, such as `web_claude_ai`, `desktop_app`, `ios`, or `scheduled_trigger`, for adoption analytics. Unset when the session has no recorded or recognized surface, and for pre-warming requests; check it with `[ -n "${CLAUDE_RUNNER_CLIENT_PLATFORM:-}" ]`, which stays safe under `set -u`. @@ -254,14 +296,42 @@ * **Use`--capacity 1` on spawned runners**: a session-bound work order registers exactly one runner bound to that session, so a higher capacity adds slots that never receive work, and the runner logs a warning at startup. * **Pre-warming work orders register unbound** : the standby runner isn’t bound to a session and claims queued work like a fixed-fleet runner. -The contract has four provisioner-agnostic rules: +The contract has four rules, whichever platform your hook provisions on: 1. **Be idempotent on`CLAUDE_RUNNER_ORDER_ID`.** Redelivery of the same request must spawn at most one runner. Derive a deterministic resource name from the order ID and let your platform reject the duplicate. Don’t key on `CLAUDE_RUNNER_SESSION_ID` instead. Every re-request for a session carries the same session ID with a new order ID, so a workload named or deduplicated by the session ID is created once and never again for that session. 2. **Don’t retry the workload.** One order ID means at most one created workload. If the runner never registers, Anthropic re-requests with a fresh order ID after `--expected-spawn-seconds`. - 3. **Use the exit-code contract.** Exit 0 means submitted. Exit 1 means retryable failure; the session backs off and is re-offered. Exit 2 or higher means non-retryable; the session is blocked from spawning again until an [Owner](</docs/en/cloud-environments#organization-shared-environments>) selects **Retry** on it in the environment’s **Activity** tab. On non-zero exit, the tail of the hook’s stderr appears there as the failure reason, so write the actionable error to stderr and never secrets. For a pre-warming request there is no session to fail: the orchestrator logs a non-zero exit locally only, and the server re-requests the spawn after the lease. - 4. **Set`--expected-spawn-seconds` to at least your p99 boot time.** This is the server-side lease. All orchestrator replicas must use the same value. + 3. **Use the exit-code contract.** Exit with the status that matches the outcome: + * **Exit 0** : submitted. + * **Exit 1** : retryable failure. The session backs off and is re-offered. + * **Exit 2 or higher** : non-retryable failure. The session is blocked from spawning again until a user sends it a new message or an [Owner](</docs/en/cloud-environments#organization-shared-environments>) selects **Retry** on it in the environment’s **Activity** tab. +On non-zero exit, the tail of the hook’s stderr appears in the **Activity** tab as the failure reason, so write the actionable error to stderr and never write secrets there. In a shell hook, keep transient failures retryable. A pre-warming request has no session to fail: the orchestrator logs a non-zero exit locally only, and the server re-requests the spawn after the `--expected-spawn-seconds` lease expires. + 4. **Set`--expected-spawn-seconds` to at least your p99 time from spawn request to runner registration.** Measure from when the orchestrator receives the spawn request, and include any wait for capacity on your platform as well as boot time. This value is the server-side lease, and the work order expires with it, so a runner whose workload takes longer can’t register. All orchestrator replicas must use the same value. Everything the hook writes to stdout or stderr appears in the orchestrator’s log with credentials automatically redacted. If sessions stay queued, check the orchestrator’s `/healthz` body for queue counts, then open your environment’s **Activity** tab on the [**Cloud environments** admin page](<https://claude.ai/admin-settings/cloud-environments>): expand a failed session there for its spawn error, and select **Retry** to re-request it. A session that stays queued with no spawn error in the **Activity** tab can mean the hook is keyed on the session ID. To confirm, check whether your platform has a workload for that session’s first spawn request and none for the re-requests. If so, key the workload on `CLAUDE_RUNNER_ORDER_ID` instead. + +#### + +​ + +Keep transient failures retryable in a shell hook + +In a shell hook that uses `set -e`, a failure that a retry could have cleared can block the session. The hook stops at the failing command and exits with that command’s own status, and the orchestrator applies the exit-code contract to that status. Many failures return a status of 2 or higher, such as `127` when a command isn’t installed and `22` from `curl --fail` on an HTTP error, so they block the session at its first failure. A session the hook has already blocked stays blocked until a user sends it a new message or an [Owner](</docs/en/cloud-environments#organization-shared-environments>) selects **Retry** on it in the environment’s **Activity** tab. To turn such a failure into exit 1 instead, put these lines directly below the hook’s `#!` line, above anything that can fail: + + set -e + PERMANENT=; permanent() { printf '%s\n' "$*" >&2; PERMANENT=1; exit 2; } + trap 'rc=$?; [ "$rc" -eq 0 ] || [ -n "${PERMANENT:-}" ] || exit 1' EXIT + +These lines change how the rest of the hook behaves, so check it for each of these patterns after you add them: + + * **Bare`exit 2` or higher**: with the trap set, it becomes exit 1. For an error that no retry can fix, call `permanent` with the reason instead, such as `permanent "namespace claude-runners does not exist"`. Call it in the main shell, not inside `$( )`, `( )`, or a pipe. + * **`exec`** : don’t start the hook’s last command with `exec`, because `exec` replaces the shell and the trap doesn’t run. + * **Second`EXIT` trap**: a second `trap ... EXIT` replaces the first, so merge the two into a single trap. Put your cleanup commands directly after `rc=$?;` and end each with `|| true;`. Cleanup then runs on failure as well as on success, and a failing cleanup command doesn’t set the hook’s exit status. This merged trap shows the shape, with `your-cleanup-command` standing in for your own: + + trap 'rc=$?; your-cleanup-command || true; [ "$rc" -eq 0 ] || [ -n "${PERMANENT:-}" ] || exit 1' EXIT + + * **Commands that are allowed to fail** : if the hook didn’t use `set -e` before, it now stops at the first command that returns non-zero, such as a lookup that finds nothing or a duplicate submit that your platform rejects. If the hook acts on the result, make that command the condition of an `if`. If it ignores the result, follow the command with `|| true`. + +To confirm the trap works, add a line directly below the `trap` line that calls a command that doesn’t exist, such as `no-such-command`. Run the hook file from your shell and check that `echo $?` prints `1`, then remove the line. ## @@ -339,8 +409,11 @@ A session that sends model requests to Amazon Bedrock or Google Cloud’s Agent Platform differs from a session on the Anthropic API in these ways: * **Policy from claude.ai** : [server-managed settings](</docs/en/server-managed-settings>) don’t reach these sessions. Neither do the organization policies an Owner sets in Claude Code admin settings, so Claude Code doesn’t enforce them inside the session. Put the rules you rely on in the runner image’s [managed settings file](</docs/en/managed-settings#delivery-mechanisms>). + * **Account skills** : these sessions don’t download the skills enabled for a person’s claude.ai account. See How each session’s config is assembled. * **Files** : files that people attach to a session in claude.ai or the mobile or desktop app don’t reach it, and Claude can’t send files back with the [`SendUserFile` tool](</docs/en/tools-reference>). Put input files in the repository or on the runner instead. - * **Model selection** : Anthropic’s control plane sends each session’s model, and when a session starts without one, Claude Code uses its default for the provider. The runner removes `ANTHROPIC_MODEL` and `ANTHROPIC_DEFAULT_MODEL` from the environment it passes to sessions. The provider pages’ examples set `ANTHROPIC_MODEL`, but in the runner’s environment neither variable has any effect. The per-family variables in Pin model versions for [Amazon Bedrock](</docs/en/amazon-bedrock#4-pin-model-versions>) and [Agent Platform](</docs/en/google-vertex-ai#5-pin-model-versions>) do reach sessions. They decide what an alias such as `opus` resolves to, not what a full model ID resolves to. + * **Model selection** : Anthropic’s control plane sends each session’s model, and when a session starts without one, Claude Code uses its default for the provider. You can’t choose the model with `ANTHROPIC_MODEL` or `ANTHROPIC_DEFAULT_MODEL` in the runner’s environment, but you can pin what an alias resolves to: + * **`ANTHROPIC_MODEL` and `ANTHROPIC_DEFAULT_MODEL`**: the runner removes them from the environment it passes to sessions, even though the provider pages’ examples set `ANTHROPIC_MODEL`. + * **Per-family pinning variables** : the variables in Pin model versions for [Amazon Bedrock](</docs/en/amazon-bedrock#4-pin-model-versions>) and [Agent Platform](</docs/en/google-vertex-ai#5-pin-model-versions>) do reach sessions. They decide what an alias such as `opus` resolves to, not what a full model ID resolves to. * **Models your account doesn’t serve** : a session can fail on a message with an error that names the model. Enable the models your developers can choose, the background model described in Pin model versions, and the classifier model that [auto mode](</docs/en/permission-modes#enable-auto-mode-on-bedrock-agent-platform-or-foundry>) uses. On Amazon Bedrock, allow each of them in your policy. * **Web search and fast mode** : [web search](</docs/en/tools-reference#websearch-tool-behavior>) isn’t available on Amazon Bedrock, and [fast mode](</docs/en/fast-mode>) isn’t available on either provider. For other capabilities that differ by provider, see [CLI capabilities that vary by provider](</docs/en/feature-availability#cli-capabilities-that-vary-by-provider>). @@ -362,6 +435,23 @@ * `<repo>/.mcp.json`: project scope. Commit the file to the repository; its servers are auto-approved in cloud sessions. In a session with several repositories, at most one repository’s file loads. When connector delivery is enabled for your organization, Anthropic’s control plane delivers the connectors you’ve configured on claude.ai to interactively-created sessions through server-provided MCP configuration, routed through `api.anthropic.com`. Sessions created programmatically, such as [CLI dispatches](</docs/en/self-hosted-environments-testing#run-the-test-loop>), don’t receive connector delivery; give them MCP servers through any of the other sources this section lists instead. The child’s OAuth token doesn’t carry a scope for fetching connectors directly, so the child doesn’t attempt that fetch itself; delivery is server-driven. `settings.json` doesn’t carry MCP server definitions, and there is no top-level `mcpServers` field in the settings schema. In managed settings, provide servers with the [`managedMcpServers`](</docs/en/settings-reference#managedmcpservers>) key instead. Sessions inherit the runner’s environment, so set [`ENABLE_TOOL_SEARCH`](</docs/en/mcp#scale-with-mcp-tool-search>) there to control MCP tool search for every session a runner spawns; the MCP page covers the values. + +### + +​ + +Wait for MCP servers before the first turn + +A self-hosted session waits briefly for MCP servers that are still connecting, at two separate points. A server that misses a wait has its tools missing when the first turn starts, and they become available later with no action on your part. The two waits are: + + * **Session startup** : before the tool list is first taken, the session waits up to 5 seconds by default for an HTTP or SSE server whose entry sets [`alwaysLoad: true`](</docs/en/mcp#exempt-a-server-from-deferral>), or for all servers when you set [`MCP_CONNECTION_NONBLOCKING=0`](</docs/en/env-vars>) in the runner’s environment. HTTP and SSE servers otherwise connect in the background. While the session waits here, it’s slower to initialize. [`MCP_CONNECT_TIMEOUT_MS`](</docs/en/env-vars>) changes the 5-second default. + * **First turn** : after the message arrives, the first turn waits up to 2 seconds for stdio servers that are still connecting. While the session waits here, the first reply is slower. To change how long this wait lasts, set [`CLAUDE_CODE_MCP_STARTUP_WAIT_MS`](</docs/en/env-vars>) in the runner’s environment. It doesn’t change which servers the wait covers. Requires Claude Code v2.1.274 or later. + +`claude mcp add` has no `alwaysLoad` flag. To set the key, add the server with `claude mcp add-json` instead, which takes it in the server’s JSON and writes it to `.claude.json`. In your Dockerfile: + + RUN claude mcp add-json core '{"type":"http","url":"https://mcp.example.com/mcp","alwaysLoad":true}' --scope user + +If a server’s tools don’t appear on later turns either, check whether the server reached the session at all, as MCP servers describes. ### @@ -509,13 +599,18 @@ How each session’s config is assembled -The runner gives each session its own config directory, seeded from a snapshot of the host’s `~/.claude/` that the runner captures once at startup: `settings.json`, `CLAUDE.md`, hooks, agents, commands, and skills in your runner image apply to every session as the user-level baseline. If you change config on a running host, the change takes effect only after you restart the runner. Set `SELF_HOSTED_RUNNER_HOST_CONFIG_DIR` to seed from a different path, or point it at an empty directory to disable seeding. Repository-committed `.claude/settings.json` layers on top as project settings. In a session with several repositories, at most one repository’s file takes effect. Sessions also read [`managed-settings.json`](</docs/en/settings#where-settings-live>) from the standard system path in your runner image. Whether its keys apply alongside [server-managed settings](</docs/en/server-managed-settings>) follows [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>): by default, when your organization delivers any server-managed keys, sessions ignore the runner image’s file apart from the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>), such as the `env` block, the sandbox locks, the sandbox binary paths, and `forceRemoteSettingsRefresh`. See [settings precedence](</docs/en/settings#settings-precedence>). When Anthropic’s control plane supplies a session with [Claude Code hooks](</docs/en/hooks>), the runner installs them alongside, not over, your own configuration. Requires Claude Code v2.1.229 or later. +The runner gives each session its own config directory, seeded from a snapshot of the host’s `~/.claude/` that the runner captures once at startup: `settings.json`, `CLAUDE.md`, hooks, agents, commands, and skills in your runner image apply to every session as the user-level baseline. If you change config on a running host, the change takes effect only after you restart the runner. Set `SELF_HOSTED_RUNNER_HOST_CONFIG_DIR` to seed from a different path, or point it at an empty directory to disable seeding. Sessions also read these settings files: + + * **Project settings** : a repository-committed `.claude/settings.json` layers on top of the user-level baseline. In a session with several repositories, at most one repository’s file takes effect. + * **Managed settings** : sessions read [`managed-settings.json`](</docs/en/settings#where-settings-live>) from the standard system path in your runner image. For whether its keys apply alongside [server-managed settings](</docs/en/server-managed-settings>), see [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>). + +For the order these sources apply in, see [settings precedence](</docs/en/settings#settings-precedence>). When Anthropic’s control plane supplies a session with [Claude Code hooks](</docs/en/hooks>), the runner installs them alongside, not over, your own configuration. Requires Claude Code v2.1.229 or later. * **Where they land** : the runner writes each supplied hook script to a reserved `hooks/.ccr-launcher/` subdirectory of the session’s config directory and registers the scripts in a separate settings file it passes to the session with `--settings`, leaving the seeded `settings.json` and your own scripts at `hooks/<name>` untouched. The runner recreates the reserved subdirectory for each session and doesn’t seed host content at `~/.claude/hooks/.ccr-launcher/` into sessions. * **Who authors them** : the control plane populates the scripts from fixed constants in its own deployment, never from per-session or third-party input. * **What still governs them** : hooks delivered through `--settings` enter the ordinary merged hook configuration, not the managed tier, so your managed settings still apply. `disableAllHooks` disables them, and they are not among the categories [`allowManagedHooksOnly`](</docs/en/settings-reference#allowmanagedhooksonly>) keeps loaded. -Outside [Claude Tag](<https://claude.com/docs/claude-tag/overview>) sessions, a session in a self-hosted environment runs with [auto memory](</docs/en/memory#auto-memory>) off by default. For instructions that should carry across sessions, use the `CLAUDE.md` in your runner image or in the repository. The runner’s snapshot of the host’s `~/.claude/` leaves out the `projects/` directory. Auto memory’s default storage location is under that directory. If you put memory files there, the runner doesn’t seed them into sessions, and they don’t turn auto memory on. +When a person starts their own session, Claude Code also downloads the [skills enabled for their claude.ai account](</docs/en/skills#skills-in-cowork-and-cloud-sessions>) into that session’s config directory. A [routine](</docs/en/routines>) run doesn’t get its owner’s skills, and a session that sends model requests to Bedrock or Agent Platform doesn’t download any. For a skill those sessions need, commit it to the repository’s `.claude/skills/` or add it to your runner image. Outside [Claude Tag](<https://claude.com/docs/claude-tag/overview>) sessions, a session in a self-hosted environment runs with [auto memory](</docs/en/memory#auto-memory>) off by default. For instructions that should carry across sessions, use the `CLAUDE.md` in your runner image or in the repository. The runner’s snapshot of the host’s `~/.claude/` leaves out the `projects/` directory. Auto memory’s default storage location is under that directory. If you put memory files there, the runner doesn’t seed them into sessions, and they don’t turn auto memory on. ###
modified Deploy self-hosted environments to production View current →
Show diff (273 lines)
--- a/self-hosted-environments-deploy.md +++ b/self-hosted-environments-deploy.md @@ -12,7 +12,10 @@ * **Ephemeral, per-session containers** : run each runner process in a fresh container or VM that’s destroyed when the process exits, with `--capacity 1` and the default `--drain-grace-sec 0` so each container serves exactly one session. At a higher capacity, or with a positive drain grace, one container serves multiple sessions from the same [locked owner](</docs/en/self-hosted-environments#key-concepts>); see [Runner lifecycle](</docs/en/self-hosted-environments#runner-lifecycle>). Don’t reuse a filesystem between runner restarts, except in the deliberate pre-warmed checkout setup, and never across owners. * When the runner stops a session, it sends no signal to a process still running after its shell command exited, such as a service that daemonized. Destroying the container or VM ends that process. - * **No broad credentials in the image** : don’t include long-lived SSH keys, cloud-provider credentials, or personal access tokens that grant more than a session needs. Mint credentials used during a session, such as push or API tokens, per session from your [wrapper script](</docs/en/self-hosted-environments-configuration#wrapper-scripts>). For the initial clone, which happens before the wrapper runs, use a [`checkout` lifecycle hook](</docs/en/self-hosted-environments-configuration#checkout>) or `--use-anthropic-git-proxy`; see Configure git. + * **No broad credentials in the image** : don’t include long-lived SSH keys, cloud-provider credentials, or personal access tokens that grant more than a session needs. Mint credentials used during a session, such as push or API tokens, per session from your [wrapper script](</docs/en/self-hosted-environments-configuration#wrapper-scripts>). The initial clone happens before the wrapper runs, so handle it with a [`checkout` lifecycle hook](</docs/en/self-hosted-environments-configuration#checkout>), or with `--use-anthropic-git-proxy` when all of a session’s repositories are on github.com. For both, see Configure git. + * **Keep the host’s GitHub credentials away from sessions** : Claude can use any GitHub credential a session can read, with whatever access that credential grants. Keep the runner host’s own broadly scoped GitHub credentials out of anything a session can read. Such a credential can be a personal access token, the token `gh auth login` saves for your account, or a `GH_TOKEN` in the runner’s environment. + * **WithAnthropic-managed git**: with such a credential, Claude reaches GitHub directly instead of through Anthropic-managed git. + * **Without Anthropic-managed git** : a clone credential can stay in the image if you scope it as tightly as Ship git config in your image describes. * **Keep the environment secret off session-running hosts** : the environment secret can register runners and pick up any session queued on the environment. On a fixed fleet it lives on every runner host, where any session’s code can read the secret file. Prefer [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>), where the secret stays on the orchestrator host, which never runs user code, and each runner receives a single-use work order that registers exactly one runner. On a fixed fleet, treat the environment-secret file as readable by every session and rotate the secret after any suspected session compromise. * **Default-deny network egress** : restrict runner and session container outbound traffic at your own network boundary on every environment; Default-deny egress covers what to allow and why. * **Least-privilege host IAM** : the compute identity attached to the runner host, such as an instance profile or node service account, should grant only what the runner itself needs. Sessions should obtain their own credentials through your wrapper script rather than inheriting the host’s. @@ -29,7 +32,7 @@ * An operator-posture override such as `sandbox.enabled: false` The guard runs regardless of [`--trust-workspace`](</docs/en/self-hosted-environments-reference#runner-cli-flags>), and doesn’t cover repository hooks, `.mcp.json`, or Bash rules; see [Permissions and tool approval](</docs/en/self-hosted-environments-configuration#permissions-and-tool-approval>) for where those grants belong. -Your organization’s IP allowlist doesn’t cover self-hosted runner traffic by default. Don’t rely on it as a network control for runner or session traffic; apply default-deny egress at your own network boundary instead, and contact your Anthropic account team if you want IP-allowlist enforcement for your organization. +If your organization has [IP allowlisting](<https://support.claude.com/en/articles/13200993-restrict-access-to-claude-with-ip-allowlisting>) enabled, add the public egress addresses of your runners and session containers to the allowlist before you start them. If you run [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>), add the orchestrator host’s address too. Don’t rely on the allowlist as a network control for runner or session traffic. Apply default-deny egress at your own network boundary instead. ## @@ -41,10 +44,10 @@ Host| Port| Used for ---|---|--- -`api.anthropic.com`| 443, HTTPS; WSS for the SCM connector only| Runner control plane and session streaming, model inference, feature flags, product analytics, [JWKS](</docs/en/self-hosted-environments-identity>) key fetches, commit signing, the git proxy when `--use-anthropic-git-proxy` is set, and the orchestrator’s [SCM connector](</docs/en/self-hosted-environments-reference#scm-connector-flags>) tunnel when `--scm-connector-host` is set -Your git host, such as `github.com` or your GitHub Enterprise host| 443 or 22| Cloning and pushing repositories. Not needed if the runner uses `--use-anthropic-git-proxy`, which routes git traffic through `api.anthropic.com`. - -Whether these hosts are needed depends on your configuration: +`api.anthropic.com`| 443, HTTPS; WSS for Anthropic-managed git| Runner control plane and session streaming, model inference, feature flags, product analytics, [JWKS](</docs/en/self-hosted-environments-identity>) key fetches, commit signing, and Anthropic-managed git when `--use-anthropic-git-proxy` is set +Your git host, such as `github.com` or your GitHub Enterprise host| 443 or 22| Cloning and pushing repositories on each git host the runner’s sessions use. On a runner that uses `--use-anthropic-git-proxy`, see when the `github.com` path is still needed. + +A runner that uses `--use-anthropic-git-proxy` routes its `github.com` git traffic through `api.anthropic.com`, so it doesn’t need the git host path for `github.com`. It still needs that path if you set `--push-outcome-on-release` or push from a `post-session` hook. Whether these hosts are needed depends on your configuration: Host| Port| When required ---|---|--- @@ -57,7 +60,15 @@ `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`. Your cloud provider’s endpoints for model requests, model lookups, and renewing credentials, such as `bedrock-runtime.us-east-1.amazonaws.com` or `aiplatform.googleapis.com`| 443| Only when the runner [sends model requests to Amazon Bedrock or Google Cloud’s Agent Platform](</docs/en/self-hosted-environments-configuration#send-model-requests-to-bedrock-or-agent-platform>) -The runner doesn’t reach `statsig.anthropic.com`, `*.sentry.io`, `claude.ai`, or `platform.claude.com`. These hosts appear in some older enterprise network checklists, but you don’t need to allowlist them for runner or session traffic: feature-flag fetches go to `api.anthropic.com`, and the runner authenticates with the environment secret rather than interactive OAuth. Two host-side flows do reach `claude.ai`, so run them from a host whose egress allows it rather than widening session-container egress: the one-line installer fetches `install.sh` from `claude.ai` at install time, and interactive `claude auth login`, which the [guided setup](</docs/en/self-hosted-environments-quickstart#set-up-an-environment-and-runner>), `doctor`’s signed-in mode, and [CI dispatch](</docs/en/self-hosted-environments-testing#authenticate-from-ci>) use, signs in through `claude.ai`, `claude.com`, and `platform.claude.com`. `mcp-proxy.anthropic.com` isn’t required either: self-hosted sessions don’t use it, and delivery of your organization’s claude.ai connectors to sessions, when enabled for your organization, routes through `api.anthropic.com`. See [MCP servers](</docs/en/self-hosted-environments-configuration#mcp-servers>). +You don’t need to allowlist these hosts for runner or session traffic: + + * **`statsig.anthropic.com`, `*.sentry.io`, `claude.ai`, and `platform.claude.com`**: these hosts appear in some older enterprise network checklists, but the runner doesn’t reach them. Feature-flag fetches go to `api.anthropic.com`, and the runner authenticates with the environment secret rather than interactive OAuth. + * **`mcp-proxy.anthropic.com`** : self-hosted sessions don’t use it. When connector delivery is enabled for your organization, your organization’s claude.ai connectors reach sessions through `api.anthropic.com`. See [MCP servers](</docs/en/self-hosted-environments-configuration#mcp-servers>). + +These host-side flows do reach `claude.ai`, so run them from a host whose egress allows it rather than widening session-container egress: + + * **The one-line installer** : fetches `install.sh` from `claude.ai` at install time. + * **Interactive`claude auth login`**: signs in through `claude.ai`, `claude.com`, and `platform.claude.com`. The [guided setup](</docs/en/self-hosted-environments-quickstart#run-the-guided-setup>), `doctor`’s signed-in mode, and [CI dispatch](</docs/en/self-hosted-environments-testing#authenticate-from-ci>) use it. The browser you sign in with also loads the claude.ai sign-in page’s browser checks from `hcaptcha.com`, `*.hcaptcha.com`, and `challenges.cloudflare.com`. ### @@ -123,7 +134,7 @@ * **Let the runner configure git** : start the runner with `--configure-git` to have it write the same identity and commit-signing config that Anthropic-hosted sessions use * **Ship git config in your image** : set identity and push credentials yourself, for example to commit under your own bot identity -Git version floors on the runner host: `--configure-git` SSH commit signing requires Git 2.34 or later, `--use-anthropic-git-proxy` requires 2.32 or later, and resuming sessions from branches pushed by [`--push-outcome-on-release`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) requires 2.29 or later. Git 2.24 is sufficient if you omit all three and manage git identity yourself. +For repositories on github.com, you can also start the runner with `--use-anthropic-git-proxy`, or set `CLAUDE_RUNNER_USE_GIT_PROXY=1`, to ask Anthropic to serve git for the runner’s sessions. Git version floors on the runner host: `--configure-git` SSH commit signing requires Git 2.34 or later, `--use-anthropic-git-proxy` requires 2.32 or later, and resuming sessions from branches pushed by [`--push-outcome-on-release`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) requires 2.29 or later. Git 2.24 is sufficient if you omit all three and manage git identity yourself. ### @@ -136,9 +147,9 @@ * `user.name = Claude` and `user.email = noreply@anthropic.com`, matching Anthropic-hosted sessions * SSH-format commit and tag signing, routed through a runner-managed shim that signs each commit via Anthropic’s signing service using the session’s own credentials. Signatures are verifiable on GitHub against Anthropic’s published SSH signing key. * `push.negotiate = true`, so git asks your git host which commits it already has before packing a push. Requires Claude Code v2.1.257 or later. - * `core.hooksPath` pointing at a runner-managed hooks directory. Its `commit-msg` and `prepare-commit-msg` hooks add a `Co-authored-by:` trailer for the session’s creator to each commit, built from the email in [`CCR_SESSION_ACCOUNT_EMAIL`](</docs/en/self-hosted-environments-configuration#wrapper-scripts>) and omitted when that variable is unset. If your image already sets `core.hooksPath`, the runner leaves your setting in place, skips installing these hooks, and prints a `[runner:git]` warning. - -Commit signing requires git 2.34 or later; the runner checks at startup and exits with an error if your git is older. This flag doesn’t configure push credentials, which you still provide in the image. On a runner on v2.1.280 or later, commits you make from a `checkout` or `post-session` lifecycle hook are signed as the session too, without the `Co-authored-by:` trailer. [Git configuration inside lifecycle hooks](</docs/en/self-hosted-environments-configuration#git-configuration-inside-lifecycle-hooks>) describes the git settings the runner fixes inside those hooks. + * `core.hooksPath` pointing at a runner-managed hooks directory. Its `commit-msg` and `prepare-commit-msg` hooks add a `Co-authored-by:` trailer for the session’s creator to each commit. The trailer is built from the email in [`CCR_SESSION_ACCOUNT_EMAIL`](</docs/en/self-hosted-environments-configuration#wrapper-scripts>) and omitted when that variable is unset. If your image already sets `core.hooksPath` and the runner doesn’t use Anthropic-managed git, the runner keeps your setting, skips installing these hooks, and prints a `[runner:git]` warning. + +Commit signing requires git 2.34 or later; the runner checks at startup and exits with an error if your git is older. This flag doesn’t configure push credentials, which you still provide in the image. On a runner on v2.1.280 or later, commits you make from a `checkout` or `post-session` lifecycle hook are signed as the session too, without the `Co-authored-by:` trailer. [Git configuration inside lifecycle hooks](</docs/en/self-hosted-environments-configuration#git-configuration-inside-lifecycle-hooks>) describes the git settings the runner fixes inside those hooks. With or without `--configure-git`, Claude Code instructs Claude to end its commit messages with a `Claude-Session: <url>` trailer and its pull request descriptions with the session’s URL. To omit both, set [`attribution.sessionUrl`](</docs/en/settings-reference#attribution-sessionurl>) to `false` in the runner host’s [`~/.claude/settings.json`](</docs/en/self-hosted-environments-configuration#how-each-session%E2%80%99s-config-is-assembled>), then restart the runner. ### @@ -174,11 +185,101 @@ Use the Anthropic git proxy -Start the runner with `--use-anthropic-git-proxy`, or set `CLAUDE_RUNNER_USE_GIT_PROXY=1`, to have it clone through Anthropic’s git proxy, authenticated with the session’s own short-lived token. For ordinary user sessions, the proxy uses the GitHub or GitHub Enterprise OAuth token stored for the session creator; for bot and agent sessions, it uses your organization’s GitHub App installation token. Either way, the runner image needs no git credentials at all: no SSH keys, no credential helper, no `.netrc`. This is the same auth path Anthropic-hosted environments use. The proxy requires `--capacity 1` because the proxy URL is per-session, and git 2.32 or later because older git ignores the configuration mechanism the proxy uses to isolate sessions from each other. The runner refuses to start if either requirement is unmet. Because the proxy fetches from Anthropic’s side, your git host must be reachable from Anthropic infrastructure, the same requirement Anthropic-hosted sessions have; for a git host that’s only routable inside your network, use a [`checkout` lifecycle hook](</docs/en/self-hosted-environments-configuration#checkout>) instead. Each runner process handles one session at a time, so run more replicas for parallelism. When the proxy is enabled, `--git-host-rewrite` and `--git-ssh-rewrite` have no effect: the proxy URL points at `api.anthropic.com`, not your git host. +With the Anthropic git proxy, also called Anthropic-managed git, the runner image needs no SSH keys, credential helper, `.netrc`, or other git credentials for the session itself. Instead, the runner asks Anthropic to serve git for its sessions. For a user’s session that Anthropic serves, the runner’s clone and the session’s own fetches and pushes go through Anthropic, which uses the GitHub OAuth token stored for the session’s creator. How Anthropic serves git for a session covers bot and agent sessions. The git proxy is off unless you turn it on. A runner that reaches your git host with its own credentials doesn’t need it, and its git works with any git host. In exchange, the git proxy limits what the runner supports and changes what it needs: + + * **github.com only** : Anthropic serves a session only when all of its repositories are on github.com, and the git proxy doesn’t support GitHub Enterprise Server yet. On a runner with the git proxy, a session with a repository on another git host fails to start. + * **Connected GitHub accounts** : the person who created a user session must have connected GitHub on claude.ai, or the session doesn’t start. + * **`--capacity 1`** : the git proxy requires one session per runner process, so run more replicas for parallelism. Turn the Anthropic git proxy on lists the requirements. + * **Replaced global git config** : the runner deletes and replaces the global git config of the user it runs as. Run it as a dedicated user or in a container. + * **Host credentials for host pushes** : the runner’s [`--push-outcome-on-release`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) push and any push your [`post-session` hook](</docs/en/self-hosted-environments-configuration#post-session>) makes still use the runner host’s own git credentials and its network path to `github.com`. For those credentials, see Ship git config in your image. + * **Per-session decision** : Anthropic decides for each session on the runner whether to serve its git, and a session it doesn’t serve fails to start. When sessions fail to start on a runner with the git proxy covers the causes. + +With `--use-anthropic-git-proxy` set, the runner deletes and replaces the global git config of the user it runs as, and keeps no backup. It does this at startup and before each session. A login or credential helper you kept there is lost. Settings that `--configure-git` writes survive. Run the runner as a dedicated user or in a container, never as your own user. + +Keep git settings that aren’t secret, such as identity and `safe.directory`, in the system git configuration. + +#### + +​ + +Turn the Anthropic git proxy on + +Before you start the runner with `--use-anthropic-git-proxy`, confirm that the runner host meets each of these requirements. The runner refuses to start when the capacity or git requirement is unmet: + + * **Claude Code v2.1.267 or later** : earlier versions accept the flag but don’t report the request for Anthropic to serve git or print the `Registering as opted in` line, so Anthropic doesn’t serve their sessions. + * **`--capacity 1`, the default**: each runner process handles one session at a time, so run more replicas for parallelism. + * **Git 2.32 or later** : older git ignores the per-session git configuration that the runner sets up for the git proxy. The Kubernetes and Docker Compose recipes on this page use `--capacity 4`. If you add `--use-anthropic-git-proxy` or `CLAUDE_RUNNER_USE_GIT_PROXY=1` to one of them without changing the capacity to `1`, the runner exits at startup every time your orchestrator restarts it. Set `--capacity 1` and run more replicas for parallelism. When the runner exits shows the line the runner prints. -The runner also reports the opt-in to Anthropic when it registers, printing `Registering as opted in to Anthropic-managed git (--use-anthropic-git-proxy)` at startup. Reporting the opt-in requires Claude Code v2.1.267 or later, and earlier versions accept the flag without reporting it or printing that line. Each session on an opted-in runner then uses either Anthropic-managed git or the per-session proxy URL. When a session uses the per-session proxy URL, the runner logs one `[runner:warn]` line saying so. +To turn the git proxy on, add `--use-anthropic-git-proxy` to the runner’s command, or set `CLAUDE_RUNNER_USE_GIT_PROXY=1` in the runner’s environment. This command, run in a shell on the runner host, starts the [quickstart](</docs/en/self-hosted-environments-quickstart#set-up-manually>)’s runner with the git proxy on: + + claude self-hosted-runner --environment-secret-file '/etc/claude/environment-secret' --base-dir '<writable-dir>' --use-anthropic-git-proxy + +At startup, the runner prints `Registering as opted in to Anthropic-managed git (--use-anthropic-git-proxy)`. Anthropic then decides for each session on that runner whether to serve its git. For each session it serves, the runner logs a `[runner:session]` line containing `governed git ACTIVE`. If a session fails to start instead, see When sessions fail to start on a runner with the git proxy. + +#### + +​ + +How Anthropic serves git for a session + +For a session that Anthropic serves, the runner’s clone and the session’s own fetches and pushes go through Anthropic, authenticated with the session’s own short-lived token: + + * **User sessions** : Anthropic uses the GitHub OAuth token stored for the session’s creator. + * **Bot and agent sessions** : Anthropic uses your organization’s GitHub App installation token. + * **URL rewrites** : `--git-host-rewrite` and `--git-ssh-rewrite` have no effect on a repository that the git proxy serves. + +#### + +​ + +When sessions fail to start on a runner with the git proxy + +On a runner started with `--use-anthropic-git-proxy`, a session fails to start when Anthropic doesn’t serve its git. Look in the runner’s log for a git error that names an `api.anthropic.com` address containing `/git_proxy/`. For each session, a runner on Claude Code v2.1.267 or later also logs either a `[runner:session]` line containing `governed git ACTIVE` when Anthropic serves the session’s git, or one `[runner:warn]` line containing `the server withheld Anthropic-managed git for this session` when it doesn’t. Find the line you’re seeing among these cases: + + * **Neither`governed git ACTIVE` nor the `withheld` line**: a runner older than Claude Code v2.1.267 logs neither line, and Anthropic doesn’t serve its sessions. Update the runner to v2.1.267 or later by following Pin the version. + * **The`withheld` line**: Anthropic didn’t serve the session. A runner that worked with the git proxy before can fail this way with no change on your side. + * **A repository isn’t on github.com** : a session with even one repository on another git host, such as GitHub Enterprise Server, isn’t served, including its github.com repositories. Turn the Anthropic git proxy off for that environment’s runners. + * **Every repository is on github.com** : report the failure to your Anthropic account team with the session ID from the `withheld` line. Anthropic records the reason on its side. + * **A line containing`remote: access denied by the git proxy`**: a session that Anthropic serves can still be refused, for example when organization policy denies git access for the session, or the session isn’t authorized for the repository. The runner’s log then shows a line containing `remote: access denied by the git proxy`, and the rest of that line says why. + * **`GitHub authentication required`** : this appears when the session’s creator has no working GitHub connection on claude.ai. The session’s clone fails, and the git error reads `GitHub authentication required. Please reconnect your GitHub account.` Ask that person to connect or reconnect GitHub in their claude.ai settings. + +After you fix the cause, start the failed sessions again. + +#### + +​ + +Turn the Anthropic git proxy off + +If sessions in an environment use a repository on a git host other than github.com, such as GitHub Enterprise Server, turn `--use-anthropic-git-proxy` off for that environment’s runners. + +1 + +Remove the flag + +Remove `--use-anthropic-git-proxy` from the runner’s command. If you set `CLAUDE_RUNNER_USE_GIT_PROXY` in the runner’s environment, such as a pod spec or a Compose file, remove it there. In a shell, unset it: + + unset CLAUDE_RUNNER_USE_GIT_PROXY + +2 + +Give the runner git credentials + +Provide credentials that work without a prompt for every git host the runners’ sessions use, github.com included. Any credential that was in the runner user’s global git config is gone, because the runner deleted that config while `--use-anthropic-git-proxy` was set. Ship credentials in your image or use a [`checkout` lifecycle hook](</docs/en/self-hosted-environments-configuration#checkout>). + +3 + +Open the network path + +Allow the runner to reach each git host the runners’ sessions use on port 443 or 22. See the git host row in Network requirements. + +4 + +Restart the runners + +Restart the runners so that they register without the git proxy. Then start each failed session again. #### @@ -245,7 +346,7 @@ FROM debian:bookworm-slim ARG CLAUDE_CODE_VERSION - RUN apt-get update && apt-get install -y --no-install-recommends git curl ca-certificates openssh-client \ + RUN apt-get update && apt-get install -y --no-install-recommends git curl ca-certificates openssh-client jq \ && rm -rf /var/lib/apt/lists/* RUN curl -fsSL "https://downloads.claude.ai/claude-code-releases/${CLAUDE_CODE_VERSION:?set with --build-arg CLAUDE_CODE_VERSION}/linux-x64/claude" \ -o /usr/local/bin/claude && chmod +x /usr/local/bin/claude @@ -350,7 +451,7 @@ kubectl create namespace claude-runners -Create the backing Secret from a local file holding the value you copied in the admin UI’s [**Copy environment key** step](</docs/en/self-hosted-environments-quickstart#set-up-an-environment-and-runner>), so the secret never appears in your shell history. Run `(umask 077 && cat > ./environment-secret)`, paste the secret, press Enter, then Ctrl-D. Then create the Secret and delete the file: +Create the backing Secret from a local file holding the value you copied in the admin UI’s [**Copy environment key** step](</docs/en/self-hosted-environments-quickstart#set-up-manually>), so the secret never appears in your shell history. Run `(umask 077 && cat > ./environment-secret)`, paste the secret, press Enter, then Ctrl-D. Then create the Secret and delete the file: kubectl create secret generic claude-runner-environment-secret -n claude-runners --from-file=environment-secret=./environment-secret @@ -464,7 +565,12 @@ Reuse a pre-warmed checkout -For large repositories, the clone can dominate session startup. At `--capacity 1` with no [`checkout` hook](</docs/en/self-hosted-environments-configuration#checkout>), the runner keeps one canonical clone per repository at `<base-dir>/<repo-owner>/<repo>` and reuses it across sessions: it fetches the requested ref, detaches `HEAD`, and resets hard to it, which is near-instant when little has changed. To skip the cold clone, supply the clone in one of two ways: +For large repositories, the clone can dominate session startup. To skip the cold clone, supply a clone yourself at the path where the runner keeps its own. With no [`checkout` hook](</docs/en/self-hosted-environments-configuration#checkout>), the runner keeps one canonical clone per repository at `<base-dir>/<repo-owner>/<repo>` and reuses it across sessions: + + * **At`--capacity 1`**: the runner fetches the requested ref, detaches `HEAD`, and resets hard to it, which is near-instant when little has changed. + * **At a`--capacity` above one**: the runner fetches into that clone, then checks out a separate worktree from it for each session. A pre-warmed clone saves the download but not the checkout. + +Supply the clone in the image or on a persistent volume: * **Clone in the image** : build the clone into your runner image at that path. Every fresh container then starts with the warm clone without reusing a disk. * **Clone on a persistent volume** : on runners you pre-lock to one user’s account with [`--lock-to-account`](</docs/en/self-hosted-environments-reference#runner-cli-flags>), point `--base-dir` at a persistent volume, so the disk only ever serves that account. A pre-locked runner never picks up Claude Tag channel sessions, so this option doesn’t apply to runners that serve them. @@ -472,7 +578,7 @@ What the reuse path does and doesn’t guarantee: * **Any clone shape works** : a full, shallow, or single-branch clone at the path is used as-is. The runner never passes `--depth` when fetching into an existing clone, so a full pre-warm keeps its full history and a shallow one stays shallow. `CLAUDE_RUNNER_FETCH_DEPTH` (`full`, `0`, or a number; default 50) controls only the cold clone the runner makes when no clone exists yet. - * **Tracked changes reset, untracked files persist** : each session starts from a hard reset that wipes the previous session’s tracked modifications, but the runner never runs `git clean`, so untracked files from the locked owner’s earlier sessions stay in the tree. + * **Tracked changes reset, untracked files persist** : at `--capacity 1`, each session starts from a hard reset that wipes the previous session’s tracked modifications, but the runner never runs `git clean`, so untracked files from the locked owner’s earlier sessions stay in the tree. * **Per-session directories persist too** : alongside the checkout, the runner creates per-session entries under `<base-dir>/_sessions/` for every session it runs. The session’s Claude config directory holds a local copy of the conversation transcript. Next to it sit the session’s uploaded files, when the session has any. The session directory sits there too: it holds any per-session worktrees and `checkout` hook checkouts while the session runs, and it keeps whatever else Claude wrote in it. By default the runner leaves these in place when the session ends, so on a disk that outlives the runner process they accumulate. Every session runs as the runner’s own user, so any later session that disk serves can read them. If you keep a persistent `--base-dir`, size the volume for that growth. The same applies to any setup that restarts the runner on the same filesystem, including the Docker Compose recipe. * **With`--remove-session-state`, per-session directories don’t persist**: start the runner with [`--remove-session-state`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) to have it delete each session’s per-session directories as the session ends. The deletion is best-effort: the directories stay when the runner is killed before its cleanup runs. The canonical clone and files a session wrote elsewhere on the host, such as the temporary directory, stay regardless. * **With the git proxy, the reset becomes a checkout** : with `--use-anthropic-git-proxy`, the runner sanitizes the clone’s `.git/` before each session, keeping the object store, refs, and shallow state but deleting the index, so each session pays a full working-tree checkout instead of a near-instant reset; it still never re-clones. Submodule pre-warms aren’t supported under the proxy. @@ -484,10 +590,12 @@ Pin the version -Each session’s child Claude Code process runs the runner’s own binary, and the runner turns off auto-update inside the sessions it spawns, so every session runs the version you installed on the host or built into the image. A host-level update takes effect the next time the runner starts. A model your sessions use can require a newer Claude Code version than the one they run. The server then rejects requests for that model with [Claude Code does not support this model](</docs/en/errors#claude-code-does-not-support-this-model>). Before you pin a version, check [the Claude Code versions that models require](</docs/en/model-config#available-models>) for every model your sessions use. - +Each session’s child Claude Code process runs the runner’s own binary, and the runner turns off auto-update inside the sessions it spawns, so every session runs the version you installed on the host or built into the image. A host-level update takes effect the next time the runner starts. Choose which version your sessions run and when it changes: + + * **Before you pin a version** : check [the Claude Code versions that models require](</docs/en/model-config#available-models>) for every model your sessions use. If a model requires a newer version than the one your sessions run, the server rejects requests for that model with [Claude Code does not support this model](</docs/en/errors#claude-code-does-not-support-this-model>). * **To hold a fleet on one version** : build the image with a pinned version, or on a bare host install a specific version and [disable auto-updates](</docs/en/setup#disable-auto-updates>) - * **To upgrade** : install the newer version or rebuild the image, then restart the runners + * **To upgrade a fixed fleet** : read the [changelog](</docs/en/changelog>) entries between your version and the one you’re installing, then install the newer version or rebuild the image and restart the runners + * **To upgrade on-demand runners** : read the [changelog](</docs/en/changelog>) entries between your version and the one you’re installing, then change the image your [`spawn-runner` hook](</docs/en/self-hosted-environments-configuration#the-spawn-runner-hook>) starts. Each new runner gets the new version. A runner that’s already up, including a standby runner that [`--min-idle`](</docs/en/self-hosted-environments-reference#orchestrator-cli-flags>) started, keeps its version until it exits. Don’t restart it, because its work order is single-use. * **Plugins** : plugin marketplaces don’t auto-update either; set `FORCE_AUTOUPDATE_PLUGINS=1` in the runner’s environment to let plugins auto-update while the binary stays pinned ## @@ -544,7 +652,8 @@ Additional limitations * **Resumed sessions lose unpushed work** : a fresh runner clones the repository again from its starting branch, so work the session hadn’t pushed is gone. - * **To keep committed work** : set [`--push-outcome-on-release`](</docs/en/self-hosted-environments-reference#runner-cli-flags>). The runner then makes a best-effort push of the session’s outcome branches before it releases, and the resumed session starts from those commits. Uncommitted changes are still lost. + * **To keep committed work** : set [`--push-outcome-on-release`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) on every runner in the environment, because a runner without the flag resumes the session from its starting branch. A runner with the flag makes a best-effort push of the session’s outcome branches before it releases, and the resumed session starts from those commits. The push uses the runner host’s own git credentials, including on a runner that uses Anthropic-managed git. Uncommitted changes are still lost. + * **With a`checkout` hook**: repositories checked out via a [`checkout` lifecycle hook](</docs/en/self-hosted-environments-configuration#checkout>) aren’t pushed. Snapshot those from the [`post-session` hook](</docs/en/self-hosted-environments-configuration#post-session>) instead. * **Before enabling the flag** : restrict who can push to `claude/*` refs on the source remote. On resume, the runner fetches the previously pushed branch without verifying who pushed it. * **A repository added mid-session can fail to clone** : Claude clones it with `git clone` over HTTPS. On a runner without `--use-anthropic-git-proxy`, the clone fails with a git authentication error if nothing on the host can read the repository. Where you can, select every repository the session needs when you create it. * **Some connectors don’t appear in self-hosted sessions** : a connector you haven’t yet connected in claude.ai Settings isn’t listed in a self-hosted session, and the session won’t prompt you to connect it. Connect it in Settings first, then start a fresh session. Adding a connector to an already-running session also doesn’t make its tools available to Claude; start a fresh session to pick up a newly added connector. @@ -572,13 +681,14 @@ * **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 owner. Check each runner’s `claude_code_self_hosted_runner_locked_account` [metric](</docs/en/self-hosted-environments-reference#prometheus-metrics>) or the `locked_account` field of its `[runner:health]` log line to see who holds it. Both show the owner’s email only after the runner has been issued a session token carrying an `act.email` claim, which a Claude Tag agent’s sessions never do. Without the claim, the runner emits no `locked_account` series and logs `locked_account=yes`, which tells you the runner is locked but not to which owner. Add replicas, or wait for an existing runner to drain and restart. If the environment uses on-demand runners, check the orchestrator instead; see [On-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>). - * **Sessions fail immediately after pickup** : open the session in claude.ai/code to see the error. The most common causes are missing git credentials in the runner image and build tools that aren’t installed. An unwritable base directory stops the runner at startup instead of failing sessions. See the **Runner exits at startup with`cannot create or write to base directory`** entry in this list. + * **Sessions 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. On a runner started with `--use-anthropic-git-proxy`, see When sessions fail to start on a runner with the git proxy. An unwritable base directory stops the runner at startup instead of failing sessions. See the **Runner exits at startup with`cannot create or write to base directory`** entry in this list. + * **Sessions fail to start on a runner that set`--use-anthropic-git-proxy`**: look in the runner’s log for `access denied by the git proxy`, or for a git error that names an `api.anthropic.com` address containing `/git_proxy/`. To tell whether Anthropic served the session and fix the cause, see When sessions fail to start on a runner with the git proxy. * **Sessions can’t reach the network through an authenticating egress proxy** : when the source you set with `--proxy-authorization-command` or `--proxy-authorization-file` fails, times out after 30 seconds, or yields an empty value, the runner answers that connection `502 Bad Gateway` and logs why. The runner redacts the command’s stderr in that log and never logs the header value. With `--proxy-authorization-command`, run the command yourself on the host to confirm it prints the whole header value on stdout. If the runner instead exits at startup with `could not start the proxy-authorization listener`, it couldn’t open its loopback listener. * **Runner logs`Poll failed` lines containing `rejecting the malformed poll response`**: the runner received a work-poll response whose body isn’t the queue’s expected JSON, most often because something between the runner and `api.anthropic.com`, such as an intercepting proxy or a captive portal, answered with its own page. The runner rejects the response, counts it under the `transport` kind of the `claude_code_self_hosted_runner_poll_errors_total` [metric](</docs/en/self-hosted-environments-reference#prometheus-metrics>), and retries on the failed-poll schedule described in [Session lifecycle](</docs/en/self-hosted-environments#session-lifecycle>). The runner keeps serving its live sessions. Configure the proxy to pass responses from `api.anthropic.com` through unaltered. Before v2.1.246, the runner read such a response as an empty work queue, which could end its live sessions or make it exit. * **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. * **A session starts without one of its repositories** : on a runner with no [`checkout` hook](</docs/en/self-hosted-environments-configuration#checkout>), the git host can refuse the runner’s access check for a repository the session only reads from. The runner then skips that repository, logs a `[runner:warn] could not access context source` line naming the refusal, and starts the session on the remaining ones. The runner skips only a clear refusal: the host answers that the repository wasn’t found, git finds no credentials for the host, or authentication fails. A network failure, a timeout, or an HTTP `403` still fails the session start, as does a refusal for a repository the session pushes results to. The runner still fails a session that skipping would leave with no repository at all. With `--use-anthropic-git-proxy`, the runner skips only a repository the git proxy itself denies. The access check runs again each time the session starts on a runner, so once the runner’s git identity has read access, the next start clones the repository. Before v2.1.274, each of these refusals failed the session start. * **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`. - * **Turns fail with a 401** : each session authenticates model calls with the short-lived [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/self-hosted-environments-configuration#wrapper-scripts>) that the runner fetches from Anthropic and rotates over the session’s stdin. When a turn ends with a 401 or 403 from the model API, the runner fetches a fresh token and passes it to the session. The failed turn isn’t retried. When a fetch fails, the runner logs an `inference_token refresh failed` line that says when it will retry, and it keeps retrying for as long as the session runs. If every call starts failing about 30 minutes into a session, a wrapper script has likely severed the session’s stdin, so token rotations can’t reach it; see [Keep stdin and file descriptor 3 attached](</docs/en/self-hosted-environments-configuration#keep-stdin-and-file-descriptor-3-attached>). Before v2.1.274, the runner stopped retrying a failed fetch after a few attempts and waited for the next scheduled one. A failed turn didn’t trigger a fetch, so every turn failed with a 401 until the next scheduled fetch. + * **Turns fail with a 401** : when a turn ends with a 401 or 403 from the Anthropic API, the runner fetches a fresh [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/self-hosted-environments-configuration#wrapper-scripts>) from Anthropic and passes it to the session. The failed turn isn’t retried. This token is short-lived, and the runner rotates it over the session’s stdin. When a fetch fails, the runner logs an `inference_token refresh failed` line that says when it will retry, and it keeps retrying for as long as the session runs. If every call starts failing about 30 minutes into a session, a wrapper script has likely severed the session’s stdin, so token rotations can’t reach it; see [Keep stdin and file descriptor 3 attached](</docs/en/self-hosted-environments-configuration#keep-stdin-and-file-descriptor-3-attached>). Before v2.1.274, the runner stopped retrying a failed fetch after a few attempts and waited for the next scheduled one. A failed turn didn’t trigger a fetch, so every turn failed with a 401 until the next scheduled fetch. * **Pod is killed mid-drain** : raise `terminationGracePeriodSeconds` to at least the value the runner logs at startup. See Shutdown timing. 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 surfaces the log’s tail alongside the session in claude.ai/code. Unless you started the runner with [`--remove-session-state`](</docs/en/self-hosted-environments-reference#runner-cli-flags>), it also keeps a failed session’s log on disk and prints its path in the runner log. @@ -593,6 +703,7 @@ * **A normal exit** : the runner finished its sessions and drained, reached its retire time, or was told to stop. Restart it so the environment has capacity again. [Runner lifecycle](</docs/en/self-hosted-environments#runner-lifecycle>) describes these exits. * **A failed start** : the runner can’t start with the configuration or host it was given, so it exits seconds after it starts, and it exits the same way every time you restart it. Restarting it faster doesn’t help. Someone needs to read its output and fix the cause. + * **Lost contact** : a runner that can’t reach Anthropic for longer than its [lease](</docs/en/self-hosted-environments#session-lifecycle>), for example while its host sleeps, can be removed from the environment. When a removed runner reconnects, it exits. Its log can show a `[runner:fatal]` line that contains `runner record gone server-side` or, after a longer outage, [`poll auth failed`](</docs/en/self-hosted-environments-quickstart#set-up-an-environment-and-runner>). The runner doesn’t register again by itself, so restart it. Configure your supervisor to restart the runner whenever it exits, to wait longer between restarts when the runner keeps exiting right after it starts, and to tell someone when that keeps happening.
modified Verify session identity in self-hosted environments View current →
--- a/self-hosted-environments-identity.md +++ b/self-hosted-environments-identity.md @@ -186,7 +186,7 @@ "$CLAUDE_RUNNER_CLAUDE_BIN" self-hosted-runner decode-token | jq -re '.act.email // .act.sub' -Wrappers receive the absolute path to the runner’s own binary in `CLAUDE_RUNNER_CLAUDE_BIN`; use that path rather than a PATH-resolved `claude` so the decode runs on the same binary the runner itself uses. Use `jq -re` rather than `jq -r` so a missing claim causes a non-zero exit. With `-r` alone, a missing claim prints the literal string `null` and exits zero, which silently passes a bad value downstream. Pass `--no-verify` to `decode-token` only for offline inspection where the JWKS endpoint is unreachable. +Wrappers receive the absolute path to the runner’s own binary in `CLAUDE_RUNNER_CLAUDE_BIN`; use that path rather than a PATH-resolved `claude` so the decode runs on the same binary the runner itself uses. Use `jq -re` rather than `jq -r` so a missing claim causes a non-zero exit. With `-r` alone, a missing claim prints the literal string `null` and exits zero, which silently passes a bad value downstream. If `decode-token` can’t fetch the keys from the JWKS endpoint or can’t verify the token, it prints the reason to stderr, prints no claims, and exits with code 1. Pass `--no-verify` to `decode-token` only for offline inspection where the JWKS endpoint is unreachable. ##
modified Self-hosted environments quickstart View current →
--- a/self-hosted-environments-quickstart.md +++ b/self-hosted-environments-quickstart.md @@ -28,6 +28,7 @@ The runner host needs: * A Linux or macOS host or container with outbound HTTPS to `api.anthropic.com`, to `claude.ai` and the download hosts it redirects to for the install step below, and to your git host for the clone; the [network requirements table](</docs/en/self-hosted-environments-deploy#network-requirements>) has the full list. Windows isn’t supported as a runner host; run the runner in a Linux container instead. Developer workstations aren’t affected, since sessions start from claude.ai in a browser. + * A repository for the test session: a public one, or one this host can already clone by its HTTPS URL without being asked for credentials. * A clock synchronized to real time, for example with NTP. Authentication fails when the clock is more than five minutes off; see [Troubleshooting](</docs/en/self-hosted-environments-deploy#troubleshooting>). ### @@ -53,11 +54,32 @@ Set up an environment and runner -Claude Code includes a guided setup: an interactive Claude Code session that walks you through creating the environment in the admin UI, starts a local runner with the secret file you save, confirms that the runner registers, and writes a cheat sheet to `./runner-setup/CHEAT-SHEET.md`. Run it on a machine where you’ve signed in with `claude auth login` using an account that holds an Owner role; it isn’t available with API keys or third-party model providers. On hosts where an interactive session isn’t possible, use the manual steps below instead. Confirm the version check passed first: on versions older than 2.1.224, this command starts an ordinary Claude session with the words as the prompt instead of the guided setup. To start the guided setup, run the setup subcommand and follow the prompts: +Use either the guided setup or the manual steps. The guided setup is a single command that starts an interactive Claude Code session and walks you through the rest. Use the manual steps instead on a host where an interactive session isn’t possible. Also use them when someone who holds the Owner role created the environment and handed you its secret, since the guided setup needs an Owner sign-in. + +### + +​ + +Run the guided setup + +The guided setup walks you through creating the environment in the admin UI, starts a local runner with the secret file you save, confirms that the runner registers, and writes a cheat sheet to `./runner-setup/CHEAT-SHEET.md`. Before you run it, confirm your sign-in and version: + + * **Sign-in** : run it on a machine where you’ve signed in with `claude auth login` using an account that holds an Owner role. With only an API key or a third-party model provider, the session starts but its organization checks fail. + * **Version** : confirm the version check passed. On versions older than 2.1.224, the setup command starts a Claude session with the words as the prompt instead of the guided setup. + +To start the guided setup, run the setup subcommand in your shell and follow the prompts: claude self-hosted-runner setup -To set up manually instead: +The setup doesn’t start a test session itself: it tells you to start one at claude.ai/code. The setup’s last step stops the runner it started. If you leave the setup before that step, the runner keeps running. To keep going after the last step, start the runner again in your shell with the command in `./runner-setup/CHEAT-SHEET.md`, then route a session to the environment. + +### + +​ + +Set up manually + +Create the environment on claude.ai, start the runner from a terminal on the host, then return to claude.ai to confirm the runner appears and route a session to it. If someone who holds the Owner role already created the environment and handed you its secret, start at step 2. 1 @@ -69,7 +91,7 @@ Start a runner -Create the secret directory. This step and the next need root for the `/etc/claude` path; any path the runner process can read works, so adjust both commands and the `--environment-secret-file` value together if you use a different one. +Create the secret directory. This command and the next use `/etc/claude`, which needs root, and the secret file they create is readable only by the user who runs them. If the runner will run as another user, it exits with `error: Failed to read environment secret file <path> (EACCES: permission denied, open '<path>')`. In that case, run both commands as the runner’s user with a directory that user can write to in place of `/etc/claude`, and pass the same path to `--environment-secret-file`. Any path the runner process can read works. mkdir -p /etc/claude @@ -77,23 +99,39 @@ (umask 077 && cat > /etc/claude/environment-secret) -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. +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`: claude self-hosted-runner --environment-secret-file '/etc/claude/environment-secret' --base-dir '<writable-dir>' + +The runner logs `Registered: runner_id=<runner-id>` once it has registered with your environment, then begins polling for work. If the runner exits later, restart it yourself. See If the runner exits for when that happens. 3 Verify the runner appears -Return to the [**Cloud environments** page](<https://claude.ai/admin-settings/cloud-environments>). Your environment’s status changes from **No runners deployed** to **Healthy** within a few seconds of the runner starting; open the environment and select **Activity** to see the runner itself. +Return to the [**Cloud environments** page](<https://claude.ai/admin-settings/cloud-environments>). Your environment’s status changes from **No runners deployed** to **Healthy** within a few seconds of the runner starting; open the environment and select **Activity** to see the runner itself. If you don’t have access to the admin page, the `Registered: runner_id=<runner-id>` line in the runner’s log from the previous step gives you the same signal. 4 Route a session to the environment -Start a session at claude.ai/code and select your environment from the environment picker, where self-hosted environments appear alongside Anthropic-hosted ones. The runner clones with whatever git credentials the host already has, so pick a repository this host can already clone, or a public one; credential options for private repositories in production are on [Configure git](</docs/en/self-hosted-environments-deploy#configure-git>). The next available runner picks up the queued session and logs `Picked up session <session-id>` along with its active count and capacity, so you can confirm from the runner’s own output which host took the session. Watch the session work and read Claude’s replies at [claude.ai/code](<https://claude.ai/code>). If the session sits queued instead, see [Troubleshooting](</docs/en/self-hosted-environments-deploy#troubleshooting>). +Start a session at claude.ai/code and select your environment from the environment picker, where self-hosted environments appear alongside Anthropic-hosted ones. For the repository, pick the one from the prerequisites: a public repository, or one this host can already clone. The runner clones with whatever git credentials the host already has.The next available runner picks up the queued session and logs `Picked up session <session-id>` along with its active count and capacity, so you can confirm from the runner’s own output which host took the session. Watch the session work and read Claude’s replies at [claude.ai/code](<https://claude.ai/code>).If the session doesn’t start working, match what you see: -The runner exits by design once its active sessions finish; see [Runner lifecycle](</docs/en/self-hosted-environments#runner-lifecycle>). For production, deploy it under an orchestrator that restarts it on exit and waits longer between restarts when the runner keeps exiting right after it starts. See [Deploy to production](</docs/en/self-hosted-environments-deploy>) and [When the runner exits](</docs/en/self-hosted-environments-deploy#when-the-runner-exits>). + * **The session sits queued** : see [Troubleshooting](</docs/en/self-hosted-environments-deploy#troubleshooting>). + * **The session fails to start with a git error** : the error appears in the session and in the runner’s log. If it includes git’s `could not read Username for` followed by your git host’s URL, the runner had no HTTPS credentials for that host. See [Configure git](</docs/en/self-hosted-environments-deploy#configure-git>), which also covers credential options for private repositories in production. + +### + +​ + +If the runner exits + +If the runner exits during this quickstart, start it again with the same command. The runner can exit on its own: + + * **Sessions finished** : the log shows `[runner:exit] account workload drained — exiting`. The runner exits by design once its active sessions finish. See [Runner lifecycle](</docs/en/self-hosted-environments#runner-lifecycle>). + * **Lost contact** : the log shows a `[runner:fatal]` line with `runner record gone server-side` or with `poll auth failed`. If the runner loses contact with Anthropic for a while, for example because the host sleeps, it can exit when it next reaches Anthropic. + +A finished turn doesn’t end your test session. After the first turn the session is still attached and the runner is still up, so you can send the session a follow-up message without restarting the runner first. For production, deploy the runner under an orchestrator that restarts it on exit and waits longer between restarts when the runner keeps exiting right after it starts. See [Deploy to production](</docs/en/self-hosted-environments-deploy>) and [When the runner exits](</docs/en/self-hosted-environments-deploy#when-the-runner-exits>). ##
modified Self-hosted environments reference View current →
--- a/self-hosted-environments-reference.md +++ b/self-hosted-environments-reference.md @@ -42,15 +42,36 @@ `--release-idle-session-min <n>`| `SELF_HOSTED_RUNNER_SESSION_IDLE_MS`| `0`| Release a session slot after N minutes of inactivity once a turn finishes or the session waits for the user’s action. A session that’s still mid-turn, including one holding a never-finishing background task or an approval requested from inside a running tool call, doesn’t count as idle; pair with `--kill-session-after-min` as the hard backstop. After a session’s background task finishes, the runner considers the session busy until the follow-up turn that reads the result starts, for at most the `SELF_HOSTED_RUNNER_BG_RESULT_GRACE_MS` window. Until the runner receives a shutdown signal or reaches its retire time, a release that leaves the runner with no active sessions starts the same exit path as a normal drain, governed by `--drain-grace-sec`. After a first signal you deferred with [`--defer-shutdown-max-min`](</docs/en/self-hosted-environments-deploy#defer-the-drain-past-the-first-signal>), the runner exits as soon as a release leaves it holding no sessions. `0` disables. `--remove-session-state [bool]`| `SELF_HOSTED_RUNNER_REMOVE_SESSION_STATE`| off| Remove a session’s per-session directories under `<base-dir>/_sessions/` when the session ends on this runner, whatever the outcome. [Reuse a pre-warmed checkout](</docs/en/self-hosted-environments-deploy#reuse-a-pre-warmed-checkout>) describes what they hold and who can read them when they stay. The removal is best-effort: the per-session directories stay in place when the runner is killed or reaches its drain deadline before cleanup runs. With the flag on, a failed or interrupted session’s debug log isn’t kept on disk. Requires Claude Code v2.1.268 or later. `--retire-at <epoch-seconds>`| `SELF_HOSTED_RUNNER_RETIRE_AT`| unset| Retire the runner at an absolute Unix timestamp in seconds, for infrastructure that kills the runner at a known time; [Runner lifecycle](</docs/en/self-hosted-environments#runner-lifecycle>) describes the release sequence and how to size the margin. Values before 2001 or after the year 5138 are rejected by the flag and ignored by the environment variable. +`--server-auto-mode-lists <mode>`| `SELF_HOSTED_RUNNER_SERVER_AUTO_MODE_LISTS`| `no-allow`| Which of the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier rule lists that the control plane sends with a session may reach that session: `all`, `no-allow`, or `none`. See Auto mode rule lists for what each value applies. An invalid value stops the runner at startup. Requires Claude Code v2.1.295 or later. `--session-stop-grace-sec <n>`| `SELF_HOSTED_RUNNER_SESSION_STOP_GRACE_MS`| `5`| How long to wait for the Claude process to exit cleanly after a session ends, before force-killing it. Raise the value if the child’s own `SessionEnd` hooks need more time. -`--startup-timeout-min <n>`| `SELF_HOSTED_RUNNER_STARTUP_TIMEOUT_MS`| `15`| Release a session slot if the child hasn’t signaled that it initialized within N minutes of spawn. Cleared by the child’s init signal on the [activity channel](</docs/en/self-hosted-environments-configuration#keep-stdin-and-file-descriptor-3-attached>), not by ordinary output, after which `--release-idle-session-min` takes over. `0` disables. +`--startup-timeout-min <n>`| `SELF_HOSTED_RUNNER_STARTUP_TIMEOUT_MS`| `15`| Release a session slot if the child hasn’t signaled that it initialized within N minutes of spawn. Cloning happens before spawn, so clone time doesn’t count. Cleared by the child’s init signal on the [activity channel](</docs/en/self-hosted-environments-configuration#keep-stdin-and-file-descriptor-3-attached>), not by ordinary output, after which `--release-idle-session-min` takes over. `0` disables. `--trust-workspace [bool]`| `SELF_HOSTED_RUNNER_TRUST_WORKSPACE`| on| Seed persisted trust for each session’s repository paths so repo-committed `permissions.allow` and `additionalDirectories` are honored. Set `false` to drop repo-committed permission grants and configure allow rules in the host config’s `settings.json` instead; repository-committed `sandbox.*` settings still apply either way, which is why the [repo-settings guard](</docs/en/self-hosted-environments-deploy#harden-your-deployment>) scans them regardless of this flag. -`--use-anthropic-git-proxy`| `CLAUDE_RUNNER_USE_GIT_PROXY=1`| off| Clone via the [Anthropic git proxy](</docs/en/self-hosted-environments-deploy#use-the-anthropic-git-proxy>) instead of customer-managed git auth. Requires `--capacity 1` and git 2.32 or later; the runner refuses to start otherwise. Supersedes the rewrite flags. +`--use-anthropic-git-proxy`| `CLAUDE_RUNNER_USE_GIT_PROXY=1`| off| Clone repositories on github.com via the [Anthropic git proxy](</docs/en/self-hosted-environments-deploy#use-the-anthropic-git-proxy>) instead of customer-managed git auth. Requires `--capacity 1` and git 2.32 or later; the runner refuses to start otherwise. Supersedes the rewrite flags. Most duration flags have a maximum, chosen to keep each timeout inside the runtime’s 32-bit timer ceiling of roughly 24.85 days. The `--*-min` flags cap at 10080 minutes, 7 days; `--drain-grace-sec` at 604800 seconds, also 7 days; and `--drain-wait-sec` at 86400 seconds, 24 hours. `--session-stop-grace-sec` and `--post-session-hook-timeout-sec` are uncapped. Overrunning a cap behaves differently per surface: * **Flag** : startup fails with an error. * **Environment variable** : the runner clamps the value to the timer ceiling rather than rejecting it. + +### + +​ + +Auto mode rule lists + +`--server-auto-mode-lists` lets you decide which [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier rules from outside the runner reach the sessions on your runners. Anthropic’s control plane can send rule lists with a session and ask the runner to apply them. Some entries may be rules an admin of your organization wrote. The lists are `environment`, `soft_deny`, and `allow`: + + * **`environment`** : an entry can make the classifier allow more as well as less. + * **`soft_deny`** : an entry blocks an action unless the user explicitly asked for it or an `allow` exception applies. + * **`allow`** : the exceptions to `soft_deny` entries. + +The flag’s value picks which lists the runner applies: + + * **`no-allow`** : the default. Applies `environment` and `soft_deny` and withholds `allow`. An `environment` entry can still make the classifier allow more, so the default doesn’t rule out every loosening. + * **`all`** : applies all three lists. + * **`none`** : applies none of them. Pick `none` to rule out every loosening from these lists. It also drops the `soft_deny` restrictions. + +No runner setting makes the control plane ask the runner to apply the lists. When it doesn’t ask, sessions receive no list whatever you set. To see which happened, start the runner with `--log-level debug`. For each session the runner then logs a line containing `the server asked this runner to apply`, or one containing `the server did not ask this runner to apply the auto mode lists it sends`. ## @@ -64,7 +85,7 @@ ---|---|--- `--hook-concurrency <n>`| `4`| Maximum `spawn-runner` hooks running in parallel. Also caps how many spawn requests are claimed per poll. `--hook-timeout <sec>`| `60`| Terminate the hook’s process tree after this many seconds. The timeout plus its 5-second kill grace must stay below `--expected-spawn-seconds`; the orchestrator enforces this at startup. -`--expected-spawn-seconds <sec>`| `120`| Expected p99 boot time for spawned runners, in the server-enforced range 10 to 3600. Sent on every poll as the server-side lease; if no runner registers before it elapses, the session is re-offered with a fresh order ID. All replicas must share this value. +`--expected-spawn-seconds <sec>`| `120`| Expected p99 time from when the orchestrator receives a spawn request to when the runner registers, including any wait for capacity on your platform. The server enforces a range of 10 to 3600. Sent on every poll as the server-side lease: if no runner registers before it elapses, the session is re-offered with a fresh order ID. All replicas must share this value. `--min-idle <n>`| `0`| Keep at least N idle session slots free by spawning standby runners proactively. `0` disables pre-warming. Pair with the runner’s `--exit-if-unused-min` so surplus standby runners reclaim themselves. `--debug-dir <path>`| unset| Write each spawn request’s work order and hook stderr to disk. Debug only; never set in production. @@ -102,6 +123,7 @@ `SELF_HOSTED_RUNNER_POST_TURN_SETTLE_MS`| `7000`| Cap on how long the runner counts a session as busy for the `--drain-wait-sec` drain after a turn finishes, while the session’s process reports the turn’s end to Anthropic. `0` or an unusable value falls back to the default, so the hold can’t be turned off. Requires Claude Code v2.1.275 or later. `SELF_HOSTED_RUNNER_SIGKILL_GRACE_MS`| `30000`| How long the runner waits for the OS to deliver `SIGKILL` to a child stuck in uninterruptible I/O before exiting itself. Floored at `--post-session-hook-timeout-sec` plus 15 seconds, and 30 more when `--push-outcome-on-release` is set, so the effective minimum is 75 seconds at defaults. `CLAUDE_RUNNER_FETCH_DEPTH`| `50`| Git fetch depth for fresh clones. Set a positive integer, or `full` or `0` for a complete fetch. Repositories already present in the workspace keep their existing depth. +`CLAUDE_RUNNER_FETCH_SERVER_PROGRESS_CAP_MS`| `600000`| How long in milliseconds, per attempt, a git fetch may wait for its first data while the git server’s own progress numbers keep rising, as when the server prepares the pack for a large repository. `0` or `off` turns the wait off: such a fetch is then cut off after two minutes without data. Any other whole number is clamped to between `120000` and `1800000`, 2 to 30 minutes. Requires Claude Code v2.1.295 or later. `CLAUDE_RUNNER_SKIP_GIT_VERIFY`| unset| When `1`, skip the `.git` presence check after a `checkout` hook runs. Set this when your hook materializes a non-git source. `FORCE_AUTOUPDATE_PLUGINS`| unset| When `1`, let plugin marketplaces auto-update even though the binary is pinned `CLAUDE_CODE_DISABLE_ARTIFACT`| unset| When `1`, disable the Artifact tool in sessions regardless of the organization’s admin setting, and drop the `*.frame.claudeusercontent.com` egress requirement @@ -168,7 +190,7 @@ `claude_code_self_hosted_orchestrator_poll_errors_total{error_kind}`| Cumulative PollSpawnHints failures by kind: `transport`, `timeout`, `5xx`, `429`, or `4xx`. All five series are present from process start; alert on `rate(...[5m]) > 0`. `claude_code_self_hosted_orchestrator_queue_pending_sessions`| Spawn requests claimable right now `claude_code_self_hosted_orchestrator_queue_backing_off_sessions`| Spawn requests in retry backoff after a retryable hook failure -`claude_code_self_hosted_orchestrator_queue_circuit_broken_sessions`| Spawn requests blocked until an Owner retries them from the environment’s **Activity** tab; alert if above zero +`claude_code_self_hosted_orchestrator_queue_circuit_broken_sessions`| Sessions blocked from spawning. Each stays blocked until a user sends it a new message or an Owner retries it from the environment’s **Activity** tab. The count can stay above zero after you fix the cause. Alert if above zero. `claude_code_self_hosted_orchestrator_pool_pending_sessions`| Total sessions waiting on a runner for this environment. Environment-wide aggregate, identical on every orchestrator instance: use `MAX` rather than `SUM` across instances. `claude_code_self_hosted_orchestrator_pool_active_sessions`| Sessions currently assigned to an alive runner in this environment. Environment-wide aggregate, identical on every orchestrator instance: use `MAX` rather than `SUM` across instances. `claude_code_self_hosted_orchestrator_spawn_hooks_total{result}`| Cumulative `spawn-runner` hook outcomes: `ok`, `retryable`, `non_retryable`. Counts orchestrator hook invocations, not session children the runners spawn: not comparable to `sessions_started_total`, since capacity above one, warm pools, and runners spawned again for the same session all diverge the two. @@ -270,7 +292,7 @@ for: 1m labels: {severity: critical} annotations: - summary: "{{ $value }} sessions circuit-broken — spawn-runner hook is repeatedly non-retryable; fix infra then retry from the Activity tab" + summary: "Sessions blocked from spawning: {{ $value }}. Read each one's error in the Activity tab, fix the cause, then select Retry" - alert: ClaudeOrchestratorPollErrors expr: sum by (pod) (rate(claude_code_self_hosted_orchestrator_poll_errors_total[5m])) > 0 for: 2m @@ -304,7 +326,7 @@ * `failed`: the child exited on its own with a non-zero code, either a crash or a setup failure after spawn. Increments `sessions_failed_total`. * `interrupted`: the runner terminated the child for an operational reason that’s neither a session success nor a runner fault, such as a drain, or terminating a session that was still on the runner when the `SELF_HOSTED_RUNNER_MAX_LIFETIME_GRACE_MS` grace window after its `--kill-session-after-min` limit ended. A Kubernetes rolling restart sending `SIGTERM` is one example of a drain. Increments `sessions_interrupted_total`. -Before v2.1.260, the runner terminated every session that reached its `--kill-session-after-min` limit and counted it in `sessions_interrupted_total`. The [`post-session` hook](</docs/en/self-hosted-environments-configuration#post-session>)’s `CLAUDE_RUNNER_EXIT_REASON` classifies clean handoffs differently. The hook reports a release, a startup timeout, and a server deassign as `interrupted`, because the runner stopped the child. These counters record the same events as `completed`, because the slot was handed back cleanly. If you reconcile hook receipts against `sessions_completed_total` directly, you undercount completions. Use the hook for per-session guarantees and the counters for aggregate rates. On a one-shot environment, `--capacity 1` with the default `--drain-grace-sec 0`, each runner process exits moments after its one session ends. `sessions_completed_total`, `sessions_failed_total`, and `sessions_interrupted_total` increment only at session end, right before that exit, so a Prometheus scrape every 15 to 60 seconds rarely catches the increment before the runner’s series disappears; these three end-of-session counters are the terminal counters the rest of this section refers to. `sessions_started_total` increments at spawn and stays visible for the life of the session, so it reliably shows up, but on a one-shot environment it reads closer to “sessions currently running” than a cumulative count. Use the series in this table for the corresponding goal instead of the terminal counters: +Before v2.1.260, the runner terminated every session that reached its `--kill-session-after-min` limit and counted it in `sessions_interrupted_total`. The [`post-session` hook](</docs/en/self-hosted-environments-configuration#post-session>)’s `CLAUDE_RUNNER_EXIT_REASON` classifies clean handoffs differently. The hook reports these as `interrupted`, because the runner stopped the child: a release, a startup timeout, a server deassign, and an archive or delete that the poll noticed first. These counters record the same events as `completed`, because the slot was handed back cleanly. If you reconcile hook receipts against `sessions_completed_total` directly, you undercount completions. Use the hook for per-session guarantees and the counters for aggregate rates. On a one-shot environment, `--capacity 1` with the default `--drain-grace-sec 0`, each runner process exits moments after its one session ends. `sessions_completed_total`, `sessions_failed_total`, and `sessions_interrupted_total` increment only at session end, right before that exit, so a Prometheus scrape every 15 to 60 seconds rarely catches the increment before the runner’s series disappears; these three end-of-session counters are the terminal counters the rest of this section refers to. `sessions_started_total` increments at spawn and stays visible for the life of the session, so it reliably shows up, but on a one-shot environment it reads closer to “sessions currently running” than a cumulative count. Use the series in this table for the corresponding goal instead of the terminal counters: Goal| Use ---|---
modified Test self-hosted environments end to end View current →
--- a/self-hosted-environments-testing.md +++ b/self-hosted-environments-testing.md @@ -79,7 +79,10 @@ The `--environment` and `--ref` dispatch flags require Claude Code v2.1.224 or later on the machine that runs the script, the same floor as the runner itself. With the hook in place and a runner started on this host, the test script: - 1. Creates a session on the test environment with `claude -p "<prompt>" --environment <environment-id> --output-format json`, run from a git checkout so the CLI can auto-detect the repository from the `origin` remote. The optional `--ref <branch>` bases the session’s checkout on a named ref instead of local HEAD. The command creates the session, prints one line of JSON containing `session_id`, and exits without waiting for Claude’s reply. + 1. Creates a session on the test environment with `claude -p "<prompt>" --environment <environment-id> --output-format json`. Run the command from a git checkout so the CLI can auto-detect the repository from the `origin` remote. The optional `--ref <branch>` bases the session’s checkout on a named ref instead of local HEAD. The command exits without waiting for Claude’s reply. What it prints tells your script the outcome: + * **Session created** : one line of JSON such as `{"ok":true,"session_id":"session_...","title":"...","url":"...","pool_id":"..."}` + * **Session creation failed** : the line `{"ok":false,"error":"..."}`, and the command exits with status 1 + * **Some earlier errors** , such as cloud sessions being unavailable for your organization or a missing prompt: the error on stderr with no JSON line, and the command exits with status 1 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. @@ -98,7 +101,14 @@ Example script -The script below runs the full loop against `$CLAUDE_TEST_ENVIRONMENT_ID`, your test environment’s `ccpool_...` ID, shown in the environment’s detail dialog on the admin page or returned by the create-environment call, and asserts on a sentinel phrase in each reply. Run it from a git checkout of the repository you want the session to work in, after starting a runner on this host with the capture hook installed and `E2E_REPLY_DIR` exported. First sign in with a claude.ai account on the machine that runs the script, as Authenticate from CI describes. Without that sign-in, the first dispatch fails with an error such as `Unable to get organization UUID for cloud session creation`. +The example script runs on the same machine as the test runner. Before you run it, prepare that machine: + + * **Repository checkout** : run the script from a git checkout of the repository you want the session to work in. + * **Runner** : start a runner on this host with the capture hook installed and `E2E_REPLY_DIR` exported. + * **Sign-in** : sign in with a claude.ai account on the machine that runs the script, as Authenticate from CI describes. + * **Environment ID** : set `CLAUDE_TEST_ENVIRONMENT_ID` to your test environment’s `ccpool_...` ID, shown in the environment’s detail dialog on the admin page or returned by the create-environment call. + +The script below runs the full loop against `$CLAUDE_TEST_ENVIRONMENT_ID` and asserts on a sentinel phrase in each reply. #!/usr/bin/env bash # End-to-end test against a self-hosted environment, using Stop-hook read-back. @@ -145,7 +155,7 @@ TURN1="e2e-probe-$(date +%s)-$$: say exactly 'ok: custom tools are reachable' and nothing else" EXPECT1="ok: custom tools are reachable" create_json=$(claude -p "$TURN1" --environment "$CLAUDE_TEST_ENVIRONMENT_ID" \ - --ref "$TEST_REPO_REF" --output-format json) + --ref "$TEST_REPO_REF" --output-format json < /dev/null) echo "create: $create_json" SESSION_ID=$(jq -er '.session_id' <<<"$create_json") @@ -156,7 +166,7 @@ # 3. Post a follow-up via the CLI. TURN2="e2e-probe-followup-$(date +%s): say exactly 'ok: follow-up delivered' and nothing else" EXPECT2="ok: follow-up delivered" - followup_json=$(claude -p "$TURN2" --cloud "$SESSION_ID" --output-format json) + followup_json=$(claude -p "$TURN2" --cloud "$SESSION_ID" --output-format json < /dev/null) echo "followup: $followup_json" jq -e '.ok == true' <<<"$followup_json" >/dev/null
modified Advanced setup View current →
--- a/setup.md +++ b/setup.md @@ -500,7 +500,7 @@ ​ -Native installation +Uninstall a native installation Remove the Claude Code binary and version files: @@ -518,7 +518,7 @@ ​ -Homebrew installation +Uninstall with Homebrew Remove the Homebrew cask you installed. If you installed the stable cask: @@ -532,7 +532,7 @@ ​ -WinGet installation +Uninstall with WinGet Remove the WinGet package: @@ -542,7 +542,7 @@ ​ -apt / dnf / apk +Uninstall with apt, dnf, or apk Remove the package and the repository configuration: @@ -566,7 +566,7 @@ ​ -npm +Uninstall with npm Remove the global npm package:
modified Stream responses in real-time View current →
--- a/streaming-output.md +++ b/streaming-output.md @@ -106,6 +106,14 @@ Without partial messages enabled, you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete content blocks), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python). +### + +​ + +Handle a stream that’s cut off + +If a stream is cut off mid-message, such as when you interrupt the turn or the connection drops, you still receive that message’s `message_stop` before the turn ends. A cut text or thinking block also gets its `content_block_stop`. A cut tool call doesn’t, so if `message_stop` arrives while a tool call’s block is still open, treat that call’s input as incomplete. Before Claude Code v2.1.290, a cut stream could end the turn without `message_stop`, so a reply you render from stream events could stay shown as in progress. The TypeScript Agent SDK bundles Claude Code v2.1.290 or later from v0.3.290, and the Python Agent SDK from v0.2.164. If a reply stays shown as in progress after the turn ends, update the SDK. + ## ​
modified Troubleshoot a mod View current →
--- a/troubleshoot.md +++ b/troubleshoot.md @@ -120,6 +120,14 @@ ​ +`code nested too deep to scan: more than 2000 scopes` + +The line starts with the mod’s name, then `hooks module did not load:`, the file, and `code nested too deep to scan: more than 2000 scopes`. A file in a hooks module can’t nest scopes, such as functions, blocks, and loops, more than [2,000 deep](</docs/en/plugins/mods/reference#limits>). [`claude plugin validate`](</docs/en/plugins/mods/create#check-what-claude-code-reads-from-your-mod>) reports the same reason. Rewrite the code so its scopes nest less deeply. + +### + +​ + No mod loads in a directory you opened for the first time You haven’t answered the trust prompt for the directory. Start an interactive session in that directory with `claude`, and accept the trust prompt it opens with. @@ -131,6 +139,14 @@ No installed plugin loads at all You started Claude Code with `--safe-mode`. Start without the flag. + +### + +​ + +Claude Code stops asking to enable hot reloading + +Claude writes a mod in an interactive session, nothing loads, and Claude Code doesn’t ask again [whether to enable hot reloading](</docs/en/plugins/mods/create#ask-claude-for-a-mod>). If the question ends three times without an answer picked, hot reloading stays off. For example, the question ends that way when you set [`askUserQuestionTimeout`](</docs/en/settings-reference#askuserquestiontimeout>) and the time passes before you answer. That setting applies here because Claude Code asks in the same [question dialog that `AskUserQuestion` uses](</docs/en/tools-reference#question-auto-continue-timeout>). A question you dismiss yourself doesn’t count toward the three. To run the mod, [copy its directory out of the mods folder](</docs/en/plugins/mods/create#use-the-mod-in-other-sessions>), then in your shell start a new session with `--plugin-dir`, as in `claude --plugin-dir ~/mods/git-branch`. ##
modified Troubleshoot installation and login View current →
Show diff (316 lines)
--- a/troubleshoot-install.md +++ b/troubleshoot-install.md @@ -11,16 +11,25 @@ What you see| Solution ---|--- `command not found: claude` or `'claude' is not recognized`| Fix your PATH +`Native installation exists but ... is not in your PATH`| Add the install directory to your PATH +`INFO: Could not find files for the given pattern(s).` from `where.exe claude`| Check whether Claude Code is installed +`zsh: permission denied: /Users/you/.zshrc` or `bash: /home/you/.bashrc: Permission denied`| Make your shell config file writable `syntax error near unexpected token '<'`| Install script returns HTML +`< was unexpected at this time` in CMD| Install script returns HTML +`The term 'System.Xml.XmlDocument' is not recognized`| Install script returns HTML `curl: (22) The requested URL returned error: 403`| Install script returned 403 `curl: (23)` or `curl: (56) Failure writing output to destination`| Check connectivity or use an alternative installer -`Killed` during install on Linux, or `Installation was killed before it could finish (exit code 137)`| Free memory or add swap space +`Killed` during install on Linux| Free memory or add swap space +`Installation was killed before it could finish`| Free memory, then rerun the installer `Raw mode is not supported` during install| Rerun the installer `EACCES: permission denied` during install| Fix the install directory’s permissions `TLS connect error` or `SSL/TLS secure channel`| Update CA certificates +`CRYPT_E_NO_REVOCATION_CHECK` or `CRYPT_E_REVOCATION_OFFLINE`| Work around blocked revocation checks `Failed to fetch version` or can’t reach download server| Check network and proxy settings +`The connection dropped while downloading the update` or `Download timed out: exceeded the total deadline`| Run the update again or set your proxy `irm is not recognized` or `The token '&&' is not a valid statement separator`| Use the right command for your shell `Cask 'claude-code' is unavailable: No Cask with this name exists`| Update Homebrew +`Cask 'claude-code@latest' is not installed`| Upgrade the cask you installed `'bash' is not recognized as the name of a cmdlet`| Use the Windows installer command `A parameter cannot be found that matches parameter name 'fsSL'`| Use the Windows installer command `Claude Code on Windows requires either Git for Windows (for bash) or PowerShell`| Install a shell @@ -107,11 +116,11 @@ Verify your PATH -If installation succeeded but you get a `command not found` or `not recognized` error when running `claude`, the install directory isn’t in your PATH. Your shell searches for programs in directories listed in PATH, and the installer places `claude` at `~/.local/bin/claude` on macOS/Linux or `%USERPROFILE%\.local\bin\claude.exe` on Windows. +If installation succeeded but you get a `command not found` or `not recognized` error when running `claude`, the install directory isn’t in your PATH. Your shell searches for programs in directories listed in PATH, and the installer places `claude` at `~/.local/bin/claude` on macOS/Linux or `%USERPROFILE%\.local\bin\claude.exe` on Windows. The installer detects this case and reports it under `Setup notes:` in its output: `Native installation exists but ~/.local/bin is not in your PATH.` on macOS and Linux, or `Native installation exists but C:\Users\you\.local\bin is not in your PATH.` on Windows. It prints the fix with that note but doesn’t change PATH itself. The [VS Code extension](</docs/en/vs-code>) does not place `claude` at this location. It bundles a private copy of the CLI inside the extension directory for its own chat panel and does not add it to PATH. If you have only installed the extension, `~/.local/bin/claude` will not exist. Run the [standalone install](</docs/en/setup>) to use `claude` from a terminal, then continue below. -Check if the install directory is in your PATH by listing your PATH entries and filtering for `local/bin`: +First check that the program is there at all, then check whether its folder is in your PATH. The PATH fix is permanent, so you apply it once. Pick your platform’s tab and run its commands there: in your terminal on macOS and Linux, or in PowerShell or Command Prompt on Windows. * macOS/Linux @@ -119,9 +128,18 @@ * Windows CMD +Check that the installer put the program in place: + + ls -la ~/.local/bin/claude + + * **`No such file or directory`** : there’s no native install. If you haven’t installed Claude Code another way, such as with npm, Homebrew, or a Linux package manager, [install Claude Code](</docs/en/setup#install-claude-code>). If you installed it another way, see Check for conflicting installations. + * **A listing for the file** : the program is there. Check your PATH next. + +List your PATH entries and filter for the install folder: + echo $PATH | tr ':' '\n' | grep -Fx "$HOME/.local/bin" -If this prints `/Users/you/.local/bin` or `/home/you/.local/bin`, the directory is in your PATH and you can skip to Check for conflicting installations. If there’s no output, add it to your shell configuration.For Zsh, the default on macOS: +If this prints `/Users/you/.local/bin` or `/home/you/.local/bin`, the directory is in your PATH and you can skip to Check for conflicting installations. If there’s no output, add it to your shell configuration with the two commands for your shell. The `echo` command saves the setting for every new terminal, and `source` applies it to the window you’re in. The `echo` command prints nothing when it succeeds.For Zsh, the default on macOS: echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc source ~/.zshrc @@ -136,13 +154,28 @@ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bash_profile source ~/.bash_profile -Alternatively, close and reopen your terminal.For other shells such as fish or Nushell, add `~/.local/bin` to your PATH using your shell’s own configuration syntax, then restart your terminal.Verify the fix worked: +Alternatively, close and reopen your terminal.If the `echo` command prints `permission denied`, see `permission denied` when adding to your PATH.For other shells such as fish or Nushell, add `~/.local/bin` to your PATH using your shell’s own configuration syntax, then restart your terminal.Verify the fix worked: claude --version +If `claude` is still not found, check these causes: + + * **The terminal predates the change** : a window that was already open keeps its old PATH, and a terminal inside an editor takes its PATH from the editor. Open a new window, or quit and reopen the editor. + * **The line wasn’t saved** : run `grep -n '.local/bin' ~/.zshrc`, using your shell’s file name. It prints the line with its line number when the line is there. If it prints nothing, run the two PATH commands again. + * **The line went to another shell’s file** : run `echo $0` to see your shell, then run the two PATH commands for that shell. + +Check that the installer put the program in place: + + Test-Path "$env:USERPROFILE\.local\bin\claude.exe" + + * **`False`** : there’s no native install. If you haven’t installed Claude Code another way, such as with npm or WinGet, [install Claude Code](</docs/en/setup#install-claude-code>). If you installed it another way, see Check for conflicting installations. + * **`True`** : the program is there. Check your PATH next. + +List your PATH entries and filter for the install folder: + $env:PATH -split ';' | Select-String '\.local\\bin' -If there’s no output, add the install directory to your User PATH: +If this prints `C:\Users\you\.local\bin`, the directory is in your PATH and you can skip to Check for conflicting installations. If there’s no output, add the install directory to your User PATH: $currentPath = [Environment]::GetEnvironmentVariable('PATH', 'User') [Environment]::SetEnvironmentVariable('PATH', "$currentPath;$env:USERPROFILE\.local\bin", 'User') @@ -151,12 +184,28 @@ claude --version +If `claude` is still not found in a new terminal, check these causes: + + * **The terminal runs inside an editor** : it takes its PATH from the editor, so quit and reopen the editor. + * **The change wasn’t saved** : run `[Environment]::GetEnvironmentVariable('PATH', 'User')` and look for `.local\bin` in the PATH it prints. If it’s missing, run the two commands again. + +Check that the installer put the program in place: + + dir "%USERPROFILE%\.local\bin\claude.exe" + + * **`File Not Found` or `The system cannot find the path specified.`**: there’s no native install. If you haven’t installed Claude Code another way, such as with npm or WinGet, [install Claude Code](</docs/en/setup#install-claude-code>). If you installed it another way, see Check for conflicting installations. + * **A listing for`claude.exe`**: the program is there. Check your PATH next. + +List your PATH entries and filter for the install folder: + echo %PATH% | findstr /i "local\bin" If there’s no output, open System Settings, go to Environment Variables, and add `%USERPROFILE%\.local\bin` to your User PATH variable. Restart your terminal.Verify the fix worked: claude --version +If `claude` is still not found in a new terminal, a terminal inside an editor takes its PATH from the editor, so quit and reopen the editor too. + ### ​ @@ -173,7 +222,7 @@ which -a claude -If this prints nothing, no `claude` is on your PATH yet. Go back to Verify your PATH.Check the three locations a `claude` binary can come from. `~/.local/bin/claude` is the native installer, `~/.claude/local/` is a legacy local npm install created by older versions of Claude Code, and the npm global list shows a `-g` install: +If this prints `claude not found`, a `no claude in` line, or nothing, no `claude` is on your PATH. The next checks show whether one is installed at all.Check the three locations a `claude` binary can come from. `~/.local/bin/claude` is the native installer, `~/.claude/local/` is a legacy local npm install created by older versions of Claude Code, and the npm global list shows a `-g` install: ls -la ~/.local/bin/claude @@ -183,13 +232,18 @@ npm -g ls @anthropic-ai/claude-code 2>/dev/null +If `ls -la ~/.local/bin/claude` printed `No such file or directory`, there’s no native install. If you haven’t installed Claude Code another way, such as with npm, Homebrew, or a Linux package manager, [install Claude Code](</docs/en/setup#install-claude-code>). If `~/.local/bin/claude` exists but `which -a claude` didn’t list it, the folder isn’t in your PATH: see Verify your PATH. + List all `claude` binaries found in your PATH: where.exe claude -Check whether the native installer placed a binary: +If this prints `INFO: Could not find files for the given pattern(s).`, no `claude` is on your PATH.Check whether the native installer placed a binary: Test-Path "$env:USERPROFILE\.local\bin\claude.exe" + + * **`True`** : the native install is there. If `where.exe` found nothing, its folder isn’t in your PATH: see Verify your PATH. + * **`False`** : there’s no native install. If you haven’t installed Claude Code another way, such as with npm or WinGet, [install Claude Code](</docs/en/setup#install-claude-code>). If you find multiple installations, keep only one. The native install at `~/.local/bin/claude` on macOS/Linux or `%USERPROFILE%\.local\bin\claude.exe` on Windows is recommended. Remove the extras: Uninstall an npm global install: @@ -276,25 +330,37 @@ Install script returns HTML instead of a shell script -When running the install command, you may see one of these errors: +The install command fails with one of these errors when what it downloaded isn’t the install script. **Bash or Zsh** : the error quotes the first line of the returned page. bash: line 1: syntax error near unexpected token `<' bash: line 1: `<!DOCTYPE html>' -On PowerShell, the same problem appears as parse errors pointing into the returned page, with `iex` trying to run HTML and CSS as PowerShell: +**PowerShell, parse errors** : the errors point into the returned page, with `iex` trying to run HTML and CSS as PowerShell. iex : At line:1 char:2310 + ... igin="anonymous"/><script type="text/javascript">!function(o,c){var n ... Missing argument in parameter list. ... -The wording varies with the PowerShell version and system language: you may see `Missing expression after unary operator '--'` or a `ParserError` with `ParseException` instead. HTML tags or CSS in the quoted text identify this failure. If you download with `-OutFile install.ps1` instead, the saved file is the same web page, so that doesn’t help either. Depending on how the request was routed, you may instead see a 403 with no HTML body: +The wording varies with the PowerShell version and system language: you may see `Missing expression after unary operator '--'` or a `ParserError` with `ParseException` instead. HTML tags or CSS in the quoted text identify this failure. If you download with `-OutFile install.ps1` instead, the saved file is the same web page, so that doesn’t help either. **PowerShell,`System.Xml.XmlDocument`**: the error names this type instead of quoting the page. + + System.Xml.XmlDocument : The term 'System.Xml.XmlDocument' is not recognized as the name of a cmdlet, function, script + file, or operable program. + +When `irm` can parse the response as XML, it returns an XML object instead of text, and `iex` then tries to run that object’s type name as a command. The install script is PowerShell code and doesn’t parse as XML, so this error also means the response was something other than the script. The wording around the type name varies with the PowerShell version and system language, but `System.Xml.XmlDocument` itself stays the same, so match on the type name. **CMD** : you see this error, followed by the HTML of the returned page. + + < was unexpected at this time. + + C:\Users\you><!DOCTYPE html>... + +The first line appears in your system language, so look for the HTML that follows it. **A 403 with no page** : depending on how the request was routed, curl reports a 403 status with no HTML body. curl: (22) The requested URL returned error: 403 -These all mean the install URL returned an HTML page or an error status instead of the install script. If the HTML page says “App unavailable in region,” Claude Code is not available in your country. See [supported countries](<https://www.anthropic.com/supported-countries>). A bare 403 with no body often has the same cause, but it can also come from a corporate proxy or firewall blocking the download. If you are in a supported country and still see the 403, work through Check network connectivity before trying the alternative installers below, since those reach the same hosts. Otherwise, this can happen due to network issues, regional routing, or a temporary service disruption. **Solutions:** - - 1. **Use an alternative install method** : On macOS, install via Homebrew: +These all mean the install URL returned a web page, an XML document, or an error status instead of the install script. If the error output quotes “App unavailable in region,” Claude Code isn’t available in your country. See [supported countries](<https://www.anthropic.com/supported-countries>). A bare 403 with no body often has the same cause, but it can also come from a corporate proxy or firewall blocking the download. If you are in a supported country and still see the 403, work through Check network connectivity before trying the alternative installers below, since those reach the same hosts. Otherwise, this can happen due to network issues, regional routing, or a temporary service disruption. **Solutions:** + + 1. **Retry after a few minutes** : the issue is often temporary. Wait and try the original command again. + 2. **Use an alternative install method** : unlike a native install, a Homebrew or WinGet install [doesn’t update itself by default](</docs/en/setup#auto-updates>). On macOS, install via Homebrew: brew install --cask claude-code @@ -303,7 +369,6 @@ winget install Anthropic.ClaudeCode Then run `claude --version` to confirm: the command prints a version number such as `2.1.211 (Claude Code)`. If the shell reports `claude` isn’t found, open a new terminal window and retry: the session you installed from keeps its old `PATH`. - 2. **Retry after a few minutes** : the issue is often temporary. Wait and try the original command again. ### @@ -326,6 +391,23 @@ ​ +`permission denied` when adding to your PATH + +If the `echo` command that adds `~/.local/bin` to your PATH prints `zsh: permission denied: /Users/you/.zshrc` or `bash: /home/you/.bashrc: Permission denied`, your user can’t write to that file and nothing was saved. In your terminal, check who owns the file, using your shell’s file name in place of `~/.zshrc`: + + ls -l ~/.zshrc + +The third field of the output is the owner. + + * **The owner is another user, such as`root`**: take ownership with `sudo chown $(whoami) ~/.zshrc`, which requires administrator rights. + * **The owner is you** : the file is read-only. Make it writable with `chmod u+w ~/.zshrc`. + +Then run the two PATH commands for your shell in Verify your PATH again. + +### + +​ + `curl: (56) Failure writing output to destination` The `curl ... | bash` command downloads the script and pipes it to Bash for execution. This error, and the related `curl: (23) Failure writing output to destination`, means Bash did not receive the complete script. Exit code 56 indicates the download itself was interrupted, and exit code 23 indicates curl could not write what it received to the pipe, usually because Bash exited early. Test that you can reach `downloads.claude.ai` with the check in Check network connectivity. If you reached the server, the original failure was likely intermittent; retry the install command. You can also [try an alternative install method](</docs/en/setup#install-claude-code>). @@ -342,6 +424,18 @@ brew install --cask claude-code If Homebrew installs an older Claude Code version than you expect, the same stale index is usually the cause. The `claude-code` cask tracks the stable channel and is typically about one week behind the latest release; for the newest version run `brew install --cask claude-code@latest` instead. See [Configure release channel](</docs/en/setup#configure-release-channel>) for the difference between the two casks. + +### + +​ + +`Cask 'claude-code@latest' is not installed` + +Homebrew offers two casks, `claude-code` and `claude-code@latest`. Running `brew upgrade --cask claude-code@latest` when that cask isn’t the one installed prints `Error: Cask 'claude-code@latest' is not installed.` To see which cask you have, run this in your terminal: + + brew list --cask | grep claude-code + +Upgrade the cask it prints. If it prints nothing, neither cask is installed. ### @@ -356,16 +450,19 @@ * PowerShell’s `Could not create SSL/TLS secure channel` * PowerShell’s `Could not establish trust relationship for the SSL/TLS secure channel` -**Solutions:** +For `CRYPT_E_NO_REVOCATION_CHECK` or `CRYPT_E_REVOCATION_OFFLINE`, go to step 4. **Solutions:** 1. **Update your system CA certificates** : On Ubuntu/Debian: sudo apt-get update && sudo apt-get install ca-certificates On macOS, the system curl uses the Keychain trust store; updating macOS itself updates the root certificates. - 2. **On Windows, enable TLS 1.2** in PowerShell before running the installer: + 2. **In Windows PowerShell 5.1, enable TLS 1.2** : [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + +Then run the installer in the same window: + irm https://claude.ai/install.ps1 | iex 3. **Check for proxy or firewall interference** : corporate proxies that perform TLS inspection can cause these errors, including `unable to get local issuer certificate` and `SELF_SIGNED_CERT_IN_CHAIN`. For the install step, make the install download trust your corporate proxy’s CA: @@ -408,6 +505,23 @@ `Failed to fetch version from downloads.claude.ai` The installer couldn’t reach the download server. This typically means `downloads.claude.ai` is blocked on your network. See Check network connectivity. + +### + +​ + +The connection dropped while downloading the update + +The connection to the download server closed while `claude install` or `claude update` was fetching the Claude Code binary, and the retries didn’t recover. Claude Code retries the download when the connection drops, the transfer stalls, or the downloaded file fails its checksum, up to three attempts in total. A completed HTTP error, such as a 404, isn’t retried because the server already answered. Before v2.1.202, a single dropped connection failed the download immediately with the bare error `aborted` instead of retrying. + + The connection dropped while downloading the update (attempt 3/3: aborted). Check your network — proxies sometimes cut off large downloads. + +The text in parentheses names which attempt failed and the underlying network error. `claude update` precedes the message with `Error: Failed to install native update` on stderr. A download that stays connected but doesn’t finish within 10 minutes fails with `Download timed out: exceeded the total deadline` instead. Claude Code doesn’t retry a timed-out download, because a connection too slow to finish inside the deadline won’t finish on an immediate retry either. The steps below apply to both messages. A proxy or gateway can close a long transfer before it finishes, and the Claude Code binary is a large download. **What to do:** + + * Run `claude update` again. On an otherwise healthy network, the download usually succeeds on the next run. For the timed-out message, run it again from a faster or less throttled network. + * If your network requires a proxy, set `HTTPS_PROXY` before running the installer or `claude update`. See Check network connectivity. + * If a corporate proxy keeps closing the transfer, ask your network team to allow the full download from `downloads.claude.ai`. See [Network access requirements](</docs/en/network-config#network-access-requirements>). + * Run `claude doctor` from your shell for installation diagnostics ### @@ -523,6 +637,22 @@ 2. **Close other processes** to free memory before installing. 3. **Use a larger instance** if possible. Claude Code requires at least 4 GB of RAM. + +### + +​ + +Installation was killed before it could finish + +The install script reports when the `claude install` step is terminated by a signal. On Linux, exit code 137 means the process received SIGKILL, and on a low-memory host that’s usually the kernel out-of-memory (OOM) killer. The script prints this explanation and exits with code 137: + + Installation was killed before it could finish (exit code 137). This usually means the system ran out of memory. + Claude Code needs roughly 512MB of free memory to install. Free up memory, then run this script again. + +For any other fatal signal, and for exit code 137 on macOS, the script prints `Installation was killed before it could finish (exit code <N>)` with the actual exit code and omits the out-of-memory explanation. The message comes from the install script macOS and Linux use, which also covers installs inside WSL; the native Windows install scripts never print it. Before v2.1.200, the script exited with only the shell’s bare `Killed` line. **What to do:** + + * Stop other processes to free memory, then rerun the installer + * Add swap space or move to a larger instance. See Install killed on low-memory Linux servers for the swap-file commands. ###
modified Agent SDK reference - TypeScript View current →
Show diff (187 lines)
--- a/typescript.md +++ b/typescript.md @@ -1535,6 +1535,7 @@ agent_id?: string; timestamp?: string; context_usage?: SDKContextUsage; + usage_report?: SDKUsageReport; user_message_uuid?: string; user_message_uuids?: string[]; resume_reason?: string; @@ -1547,7 +1548,13 @@ * `'account_on_hold'`: [your account is on hold](</docs/en/errors#your-account-is-on-hold>) * `'cloud_credential_error'`: Claude Code couldn’t obtain usable AWS or Google Cloud credentials on the machine it runs on, so no request reached the cloud provider. The usual cause is a cloud sign-in that expired or was never completed on that machine, though a briefly unreachable credential service reports the same value. See [Could not load AWS or Google Cloud credentials](</docs/en/errors#could-not-load-aws-or-google-cloud-credentials>). Requires TypeScript Agent SDK v0.3.267 or later, which bundles Claude Code v2.1.267 -`aborted` is `true` when an interrupt or abort truncated the assistant message before the stream completed: the message has no `stop_reason` and the content may end mid-word. The field is absent on normally completed messages. It requires Agent SDK v0.3.214 or later. `agent_id` identifies the subagent that produced the message and is absent on main-thread messages. The value equals the `task_id` on that subagent’s `task_started` and other task events, and is unchanged when the subagent is [resumed](</docs/en/agent-sdk/subagents#resume-subagents>). The field requires Agent SDK v0.3.292 or later. Match a subagent’s messages to its task events on `agent_id` rather than pairing a message’s `parent_tool_use_id` with a task event’s `tool_use_id`. When a tool call resumes the subagent, the task events carry that call’s `tool_use_id`, while the messages keep the `parent_tool_use_id` of the tool call that first started the subagent, so the two no longer match. Claude Code sets `user_message_uuid` and `user_message_uuids` on the turn’s first assistant message, under the conditions in `user_message_uuid`. When Claude Code re-runs a turn that a restart interrupted, the re-run’s assistant messages that carry those fields also carry `resume_reason`. `timestamp` is the ISO 8601 time when the message’s content finished generating on the process that produced it. The value comes from that machine’s clock, so use it for display only and don’t order messages by it. One API turn can produce several assistant messages that share a `message.id`, each with its own `timestamp`. When the field is absent, fall back to the time you received the message. `context_usage` is a structured copy of the `/context` report, typed as `SDKContextUsage`, and requires Agent SDK v0.3.232 or later. When you send `/context` as a prompt, Claude Code delivers the report as an assistant message whose `message.content` holds the markdown table, and attaches `context_usage` to that same message. Claude Code doesn’t set the field on any other assistant message, and earlier versions deliver the `/context` table without it, so read the breakdown from the field when it’s present and fall back to the markdown text when it isn’t. +`aborted` is `true` when an interrupt or abort truncated the assistant message before the stream completed: the message has no `stop_reason` and the content may end mid-word. The field is absent on normally completed messages. It requires Agent SDK v0.3.214 or later. `agent_id` identifies the subagent that produced the message and is absent on main-thread messages. The value equals the `task_id` on that subagent’s `task_started` and other task events, and is unchanged when the subagent is [resumed](</docs/en/agent-sdk/subagents#resume-subagents>). The field requires Agent SDK v0.3.292 or later. Match a subagent’s messages to its task events on `agent_id` rather than pairing a message’s `parent_tool_use_id` with a task event’s `tool_use_id`. When a tool call resumes the subagent, the task events carry that call’s `tool_use_id`, while the messages keep the `parent_tool_use_id` of the tool call that first started the subagent, so the two no longer match. Claude Code sets `user_message_uuid` and `user_message_uuids` on the turn’s first assistant message, under the conditions in `user_message_uuid`. When the turn continues one that a restart interrupted, the assistant messages that carry those fields also carry `resume_reason`. `timestamp` is the ISO 8601 time when the message’s content finished generating on the process that produced it. The value comes from that machine’s clock, so use it for display only and don’t order messages by it. One API turn can produce several assistant messages that share a `message.id`, each with its own `timestamp`. When the field is absent, fall back to the time you received the message. `context_usage` is a structured copy of the `/context` report, typed as `SDKContextUsage`, and requires Agent SDK v0.3.232 or later. When you send `/context` as a prompt, Claude Code delivers the report as an assistant message whose `message.content` holds the markdown table, and attaches `context_usage` to that same message. Claude Code doesn’t set the field on any other assistant message, and earlier versions deliver the `/context` table without it, so read the breakdown from the field when it’s present and fall back to the markdown text when it isn’t. `usage_report` is a structured copy of the `/usage` report, typed as `SDKUsageReport`, and requires Agent SDK v0.3.273 or later. When you send `/usage` as a prompt, Claude Code delivers the report as an assistant message whose `message.content` holds the text. It attaches `usage_report` to that same message only when the session meets all of these conditions: + + * The session authenticates with a claude.ai credential + * The credential shows a known plan type or carries the `user:profile` scope + * The account isn’t on usage-based billing + +A `claude setup-token` token passed as `CLAUDE_CODE_OAUTH_TOKEN` doesn’t qualify by default, because it carries only the `user:inference` scope. Other sessions, such as API-key sessions, deliver the text without the field, and so do earlier versions. Read the report from the field when it’s present and fall back to the text when it isn’t. ### @@ -1574,7 +1581,12 @@ inline_pastes?: string[]; }; -Set `pasted_content` to send content the user pasted into your prompt UI rather than typed, one entry per paste, each a string or an array of content blocks. Claude Code appends each entry’s text after the typed text, in order, and may wrap each paste in `<pasted_content>` tags. Blocks other than text are ignored, so send images and documents in `message.content`. Requires Agent SDK v0.3.277 or later. Set `inline_pastes` to tell Claude Code which parts of `message.content` the user pasted rather than typed, one string per paste. The prompt text stays where the user put it. Claude Code may wrap each listed paste in `<pasted_content>` tags where it stands, so Claude can tell pasted material from the user’s own words. Only pastes in the prompt’s last text block are wrapped. Requires TypeScript Agent SDK v0.3.280 or later. Set `shouldQuery`, `client_composed`, or `priority` to change how Claude Code handles a message you send: +Set `pasted_content` to send content the user pasted into your prompt UI rather than typed, one entry per paste, each a string or an array of content blocks. Claude Code appends each entry’s text after the typed text, in order, and may wrap each paste in `<pasted_content>` tags. Blocks other than text are ignored, so send images and documents in `message.content`. Requires Agent SDK v0.3.277 or later. Set `inline_pastes` to tell Claude Code which parts of `message.content` the user pasted rather than typed, one string per paste. The prompt text stays where the user put it. Claude Code may wrap each listed paste in `<pasted_content>` tags where it stands, so Claude can tell pasted material from the user’s own words. Only pastes in the prompt’s last text block are wrapped. Requires TypeScript Agent SDK v0.3.280 or later. Each paste field has a size limit: + + * `pasted_content`: if the entries plus the content blocks inside them number more than 1,000, Claude Code ignores the whole field. + * `inline_pastes`: Claude Code uses the first 100 entries that aren’t blank and ignores the rest. + +Set `shouldQuery`, `client_composed`, or `priority` to change how Claude Code handles a message you send: * `shouldQuery`: set it to `false` to append the message to the transcript without triggering an assistant turn. The message is held and merged into the next user message that does trigger a turn. Use this to inject context, such as the output of a command you ran out of band, without spending a model call on it. * `client_composed`: set it to `true` to have Claude Code deliver the message text as written. Claude Code then doesn’t expand `@path` or [`@server:resource`](</docs/en/mcp#use-mcp-resources>) mentions, and doesn’t run text that starts with `/` as a command. While the `verbatimPrompts` option is on, the SDK sets the field on every message. Requires TypeScript Agent SDK v0.3.280 or later and Claude Code v2.1.248 or later. @@ -1714,7 +1726,7 @@ * `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 message you sent that this turn answered. See `user_message_uuid` for which results carry it. * `user_message_uuids`: the `uuid`s of every message you sent that Claude Code answered in this turn. See `user_message_uuids`. - * `resume_reason`: why Claude Code re-ran this turn after a restart interrupted it. Present on both arms. See `resume_reason`. + * `resume_reason`: why this turn continues one that a restart interrupted. Present on both arms. See `resume_reason`. * `local_command`: the name of the command the turn dispatched, on the success result of a turn that a command completed without entering the agent loop, such as `/compact`. The name is folded to lowercase letters and underscores, so `/reload-plugins` reports `reload_plugins`. A command that an MCP server provides, and the built-in `/mcp`, report `mcp`. A command you defined yourself reports `custom`. The arguments are never included. Absent on every turn that entered the agent loop and on sends that ran no command. Requires Agent SDK v0.3.268 or later. * `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`, on a success result with `is_error` false whose turn sent an API request. * `first_content_frame_ms`: time in milliseconds until the first `content_block_start` or `content_block_delta` stream event, counting thinking blocks as content. Present on the success arm only, when `is_error` is false. Requires Agent SDK v0.3.260 or later. @@ -1756,7 +1768,7 @@ * **A regular message you sent** , meaning one without `isSynthetic: true`: the turn answers that message for its whole run. When you send several messages close together, Claude Code can merge them into one turn, and the field then carries only the last message’s `uuid`. To match the reply to any of the merged messages, use `user_message_uuids`. * **A message you sent with`isSynthetic: true`**: the turn answers that message at first. If Claude Code picks up a regular message of yours between tool calls, the turn answers the picked-up message from then on. Echoing a synthetic message’s `uuid` requires Agent SDK v0.3.265 or later; earlier versions echo nothing on synthetic turns. - * **The prompt Claude Code generates to re-run an interrupted turn under[`CLAUDE_CODE_RESUME_INTERRUPTED_TURN`](</docs/en/env-vars>)**: when the interrupted turn’s last prompt is a regular message you sent, whether it opened the turn or Claude Code picked it up during the turn, the re-run answers that message at first. `resume_reason` tells the re-run’s frames from the interrupted attempt’s. When the last prompt isn’t a regular message of yours, the re-run answers no message of yours at first. If Claude Code picks up a regular message of yours between tool calls, the turn answers the picked-up message from then on. Echoing the interrupted turn’s prompt requires Agent SDK v0.3.268 or later. + * **The prompt Claude Code generates to continue an interrupted turn under[`CLAUDE_CODE_RESUME_INTERRUPTED_TURN`](</docs/en/env-vars>)**: when the interrupted turn’s last prompt is a regular message you sent, whether it opened the turn or Claude Code picked it up during the turn, the continued turn answers that message at first. `resume_reason` tells the continued turn’s frames from the interrupted attempt’s. When the last prompt isn’t a regular message of yours, the continued turn answers no message of yours at first. If Claude Code picks up a regular message of yours between tool calls, the turn answers the picked-up message from then on. Echoing the interrupted turn’s prompt requires Agent SDK v0.3.268 or later. * **Any other prompt Claude Code generated itself** : the turn answers no message of yours at first and its frames carry no echo. If Claude Code picks up a regular message of yours between tool calls, the turn answers that message from then on. The pickup echo requires Agent SDK v0.3.265 or later; earlier versions echo nothing on these turns. Claude Code echoes the answered message’s `uuid` on three kinds of frame: @@ -1786,12 +1798,12 @@ `resume_reason` -Why Claude Code re-ran this turn after a restart. Claude Code sets this field on a turn it re-ran under [`CLAUDE_CODE_RESUME_INTERRUPTED_TURN`](</docs/en/env-vars>), so you can tell the re-run’s reply and result from the interrupted attempt’s. Requires Agent SDK v0.3.268 or later. Claude Code sets the field on two kinds of frame: - - * **The re-run’s result** : on the success and error arms alike, whether or not the result carries `user_message_uuid`. - * **The re-run’s reply frames** : those that carry `user_message_uuid`. - -The value is a short lowercase token naming why the turn was re-run, such as `interrupted_turn`. +Why this turn continues one that a restart interrupted. Claude Code sets this field on a turn that continues an interrupted one under [`CLAUDE_CODE_RESUME_INTERRUPTED_TURN`](</docs/en/env-vars>), so you can tell the continued turn’s reply and result from the interrupted attempt’s. Requires Agent SDK v0.3.268 or later. Claude Code sets the field on two kinds of frame: + + * **The continued turn’s result** : on the success and error arms alike, whether or not the result carries `user_message_uuid`. + * **The continued turn’s reply frames** : those that carry `user_message_uuid`. + +The value is a short lowercase token, such as `interrupted_turn`. #### @@ -1946,7 +1958,7 @@ resume_reason?: string; }; -Claude Code sets `user_message_uuid` and `user_message_uuids` on the turn’s first non-ping stream event, and again when the message that the turn is answering changes, under the conditions in `user_message_uuid`. When Claude Code re-runs a turn that a restart interrupted, the re-run’s stream events that carry those fields also carry `resume_reason`. +Claude Code sets `user_message_uuid` and `user_message_uuids` on the turn’s first non-ping stream event, and again when the message that the turn is answering changes, under the conditions in `user_message_uuid`. When the turn continues one that a restart interrupted, the stream events that carry those fields also carry `resume_reason`. ### @@ -2162,6 +2174,75 @@ * `free`: the remaining window * `buffer`: the compaction reserve * `deferred`: tool schemas Claude Code holds out of the window and excludes from the usage calculation, listed for awareness + +### + +​ + +`SDKUsageReport` + +Structured form of the `/usage` report, carried as `usage_report` on the `SDKAssistantMessage` that delivers a `/usage` result. Agent SDK v0.3.273 and later export the type. The type is experimental: its shape may change. + + type SDKUsageReport = { + session: { + total_cost_usd: number; + total_api_duration_ms: number; + total_duration_ms: number; + total_lines_added: number; + total_lines_removed: number; + model_usage: { [modelName: string]: ModelUsage }; + }; + rate_limits: { + limits: + | { + kind: string; + group: string; + percent: number; + resets_at: string | null; + scope?: { + model?: { display_name: string } | null; + surface?: { display_name: string } | null; + } | null; + severity: string; + is_active: boolean; + }[] + | null; + extra_usage?: { + is_enabled: boolean; + monthly_limit: number | null; + used_credits: number | null; + utilization: number | null; + currency?: string | null; + } | null; + } | null; + }; + +The top-level fields are `session` and `rate_limits`: + + * `session`: Claude Code’s running cost and usage totals, read from the same ledger as `total_cost_usd` and `modelUsage` on `SDKResultMessage`. Each `model_usage` entry is a `ModelUsage`. + * `rate_limits`: the plan’s usage rows in `limits` and usage-credits spend in `extra_usage`. It is `null` when Claude Code couldn’t get the plan’s usage, for example when the session’s OAuth token lacks the `user:profile` scope. + +Claude Code computes `session.total_cost_usd` locally from token counts, so it is an estimate and not what your plan bills. The usage-credits spend the server reports is the separate `extra_usage` block. See [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for the accuracy caveats. `limits` holds the server’s usage rows as the server sent them: which meters apply, their scope, labels, severity, and order are the server’s, so render the rows verbatim. + + * An empty array means the server reported no meters. + * `null` means Claude Code has no rows to report. + +Each row of `limits` describes one usage meter: + +Field| Type| Description +---|---|--- +`kind`| `string`| The server’s meter kind, such as `session`, `weekly_all`, or `weekly_scoped`. Classify a row on this, never on a label +`group`| `string`| The server’s row group, such as `session` or `weekly`. Rows render grouped under it, in the server’s order +`percent`| `number`| Share of the window used, 0-100 +`resets_at`| `string | null`| ISO 8601 timestamp when the window resets +`scope`| `object | null`| Optional. What a scoped row is for, a model or a surface, with the server’s display label +`severity`| `string`| The server’s reading of the row for a meter’s color, such as `normal`, `warning`, or `critical` +`is_active`| `boolean`| `true` on the row the server picks for a single-value indicator to show + +Before Agent SDK v0.3.277, the type declared `severity` and `is_active` as optional and nullable, and a row could arrive without them. `extra_usage` is the [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) spend and cap for the billing period as the server reports them, present when the plan has usage credits. Amounts are in minor units of `currency`, cents for USD. + + * `monthly_limit` is `null` when this account has no spending cap of its own. On Team and Enterprise plans, don’t render `null` as unlimited. + * `is_enabled` is `false` while usage credits can’t pay for requests. ### @@ -3396,7 +3477,7 @@ ---|---|--- `script`| `string`| Inline workflow script. Must begin with `export const meta = { name, description }` as a literal, followed by the script body using `agent()`, `parallel()`, `pipeline()`, and `phase()`. An optional `phases` array in `meta` groups agents under named stages in the progress view `name`| `string`| Name of a built-in workflow or one saved in `.claude/workflows/`. Resolved to a script -`scriptPath`| `string`| Path to a workflow script file on disk. Takes precedence over `script` and `name`. Claude Code persists every invocation’s script and returns the path in the result, so you can edit that file and re-invoke with the same `scriptPath` to iterate +`scriptPath`| `string`| Path to a workflow script file on disk, such as the `scriptPath` a previous run returned. Takes precedence over `script` and `name`. Claude Code rejects `scriptPath` with an error when the session’s tools don’t include `Read` `args`| `unknown`| Input value exposed to the script as the global `args`, for parameterized named workflows such as a research question or a list of file paths. Pass arrays and objects as actual JSON values, not as a JSON-encoded string `resumeFromRunId`| `string`| Run ID of a prior `Workflow` invocation to resume. Completed `agent()` calls with unchanged inputs usually return cached results; the rest run live. [Resume after a pause](</docs/en/workflows#resume-after-a-pause>) covers which completed calls re-run. Same session only `title`| `string`| Ignored; the script’s `meta` block sets the title @@ -5475,6 +5556,7 @@ task_id: string; tool_use_id?: string; status: "completed" | "failed" | "stopped"; + reason?: "worker_restart"; output_file: string; summary: string; ambient?: boolean; @@ -5488,7 +5570,7 @@ session_id: string; }; -When Claude Code [moves a long MCP tool call to the background](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), the `tool_result` block for that call holds only a placeholder and the call’s real result arrives in this notification. Match the notification to the call with `tool_use_id`. On a `completed` notification, `resource_links` lists the files the tool returned by reference as `SDKMcpResourceLink` entries, with the same 50-link and 64 KiB limits as `tool_use_result.resourceLinks`. Claude Code omits `resource_links` when the result had no links and on notifications for tasks that aren’t MCP tool calls. `resource_links` requires Agent SDK v0.3.257 or later. 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. +`reason` is set when a task ends for a cause other than its own completion, failure, or stop, and requires Agent SDK v0.3.273 or later. Claude Code sets it only in sessions that connect through claude.ai: cloud sessions, including those on self-hosted runners, and Remote Control sessions. A local `query()` call never sets it. Its one value, `worker_restart`, means the Claude Code process that was running the task restarted. The notification carries status `"stopped"`, so treat the task as neither completed nor failed. When Claude Code [moves a long MCP tool call to the background](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), the `tool_result` block for that call holds only a placeholder and the call’s real result arrives in this notification. Match the notification to the call with `tool_use_id`. On a `completed` notification, `resource_links` lists the files the tool returned by reference as `SDKMcpResourceLink` entries, with the same 50-link and 64 KiB limits as `tool_use_result.resourceLinks`. Claude Code omits `resource_links` when the result had no links and on notifications for tasks that aren’t MCP tool calls. `resource_links` requires Agent SDK v0.3.257 or later. 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. ###
modified Use Claude Code in VS Code View current →
--- a/vs-code.md +++ b/vs-code.md @@ -114,6 +114,7 @@ * **Side questions** : type `/btw` followed by a question 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-reference#cleanupperioddays>) 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. * **Copy a response** : hover over a response and click **Copy response** to copy it to your clipboard, or type `/copy` to copy the latest response. `/copy 2` copies the second-to-last. Requires Claude Code v2.1.277 or later. * **Bookmarks** : hover over a response and click **Bookmark response** to save it, or click **Remove bookmark** on a saved response to remove it. To review saved responses, open the Bookmarks panel: click the bookmark icon at the top of the Claude Code panel, select **Bookmarks** in the Context section of the command menu, or type `/bookmarks`. Requires Claude Code v2.1.286 or later. + * **Files Claude sends you** : when the session is connected to [Remote Control](</docs/en/remote-control#start-a-remote-control-session>) and Claude sends you files with the [`SendUserFile` tool](</docs/en/tools-reference>), the conversation shows a row such as **Sent report.md, chart.png**. Click a file’s name to open it in the editor. * **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. * **Prompt cache clock** : a clock icon next to the context indicator estimates how much time the conversation’s [prompt cache](</docs/en/prompt-caching>) has left before it expires. It counts down from the cache’s five-minute or one-hour [lifetime](</docs/en/prompt-caching#cache-lifetime>), and each response that uses the cache restarts the countdown. Apart from compaction, the [actions that invalidate the cache](</docs/en/prompt-caching#actions-that-invalidate-the-cache>) don’t reset the clock, so it can still show minutes left after you switch models. * Until the countdown runs out, the icon shows the minutes left, such as **12m**. @@ -392,7 +393,7 @@ @browser go to localhost:3000 and check the console for errors -You can also open the attachment menu to select specific browser tools like opening a new tab or reading page content. Claude opens new tabs for browser tasks and shares your browser’s login state, so it can access any site you’re already signed into. To have each session connect to your browser as it starts, without typing `@browser`, see [Enable Chrome by default](</docs/en/chrome#enable-chrome-by-default>). For when Claude Code asks you before a browser action in a session connected that way, see [Permission prompts in VS Code sessions](</docs/en/chrome#permission-prompts-in-vs-code-sessions>). For setup instructions, the full list of capabilities, and troubleshooting, see [Use Claude Code with Chrome](</docs/en/chrome>). +You can also open the attachment menu to select specific browser tools like opening a new tab or reading page content. Claude opens new tabs for browser tasks and shares your browser’s login state, so it can access any site you’re already signed into. To have each session connect to your browser as it starts, without typing `@browser`, see [Enable Chrome by default](</docs/en/chrome#enable-chrome-by-default>). For when Claude Code asks you before a browser action, see [Permission prompts in VS Code sessions](</docs/en/chrome#permission-prompts-in-vs-code-sessions>). For setup instructions, the full list of capabilities, and troubleshooting, see [Use Claude Code with Chrome](</docs/en/chrome>). ## @@ -497,6 +498,7 @@ `useCtrlEnterToSend`| `false`| Use Ctrl/Cmd+Enter instead of Enter to send prompts `scrollToBottomOnSend`| `true`| Scroll the conversation to the bottom when you send a message. When off, the conversation stays where you left it. Requires Claude Code v2.1.275 or later `showMessageTimestamps`| `true`| Show when each message was sent. A date line marks where the day changes. Requires Claude Code v2.1.284 or later. Before v2.1.290, the default was `false` +`spinnerVerbs`| `{"mode": "append", "verbs": []}`| Set the verbs the conversation spinner rotates through while a turn runs, with the same `mode` and `verbs` fields as the CLI’s [`spinnerVerbs`](</docs/en/settings-reference#spinnerverbs>). `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. `archiveInactiveSessions`| `14`| Archive a session automatically after this many days without activity: `1`, `2`, `7`, or `14`. Set `0` to turn it off. Requires Claude Code v2.1.265 or later